DbContext-扩展方法-支持存储过程

一、方法封装

  public static  class DbContextExtension
    {
        public static List<T> GetList<T>(this DbContext db, string sql, CommandType type=CommandType.Text, params DbParameter[] parameters)
        {
            try
            {
                using (DbConnection conn = db.Database.Connection)
                {
                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    using (DbCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = sql;
                        cmd.CommandType = type;
                        cmd.Parameters.AddRange(parameters);
                        DataTable dt = new DataTable();
                        using (DbDataReader reader = cmd.ExecuteReader())
                        {
                            dt.Load(reader);
                        }
                        cmd.Parameters.Clear();
                        string json = dt.ToJson();
                        List<T> list = json.ToObject<List<T>>();
                        return list;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }

二、方法调用

          int code = 0;
                SqlParameter[] param = { 
                    new SqlParameter("@year",year),
                    new SqlParameter("@userId",userId),
                    new SqlParameter("@code ",code){ Direction=ParameterDirection.Output}
                };
                List<EChartsDto<int>> data = new List<EChartsDto<int>>();

                data = db.GetList<EChartsDto<int>>("[dbo].[proc_getRecordsByUser]", CommandType.StoredProcedure, param);

 

DbContext-扩展方法-支持存储过程

上一篇:SqlServer--常用数据查询


下一篇:数据库性能优化