一、方法封装
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);