使用EF Core框架能快速的幫助咱們進行常規的數據處理和項目開發,可是ORM雖然好用,可是在許多複雜邏輯的數據處理時,我我的仍是偏向用SQL和存儲過程的方式去處理,可是研究了一下目前最新版本的EF Core(我用的是2.1)以及相關文檔,貌似沒有找到能夠很好支持原始SQL開發的方案,因而就本身簡單的擴展了一下sql
首先說一下我查閱文檔找到已知的EF Core能夠執行SQL和存儲過程的兩個函數ExecuteSqlCommand()和FromSql()框架
1,ExecuteSqlCommand(),代碼中的EntityContext即爲數據框架上下文對象,這種方法能夠執行sql或者存儲過程而且傳遞參數,可是缺點就是函數的返回結果爲int類型的受影響行數,沒法返回指定的數據集異步
private EntityContext context = null; public ValuesController(EntityContext _context) { context = _context; } /// <summary> /// 測試代碼 /// </summary> /// <returns></returns> [HttpPost("Post")] public int Post() { long uid = 4; int data = context.Database.ExecuteSqlCommand($"exec proc_test {uid}", uid); return data; }
2,FromSql()能夠用來執行帶參數的sql,這個函數的用法以及優缺點能夠看官方文檔的這篇文章函數
https://docs.microsoft.com/en-us/ef/core/querying/raw-sql測試
3,用DbCommand 簡單的擴展數據框架上下文對象,使其能夠執行存儲過程並返回你想要的數據類型ui
public static class ExtendDBContext { /// <summary> /// 執行SQL返回受影響的行數 /// </summary> public static int ExecSqlNoQuery<T>(this EntityContext db, string sql, SqlParameter[] sqlParams = null) where T : new() { return ExecuteNoQuery<T>(db, sql, sqlParams); } /// <summary> /// 執行存儲過程返回IEnumerable數據集 /// </summary> public static IEnumerable<T> ExecProcReader<T>(this EntityContext db, string sql, SqlParameter[] sqlParams = null) where T : new() { return Execute<T>(db, sql, CommandType.StoredProcedure, sqlParams); } /// <summary> /// 執行sql返回IEnumerable數據集 /// </summary> public static IEnumerable<T> ExecSqlReader<T>(this EntityContext db, string sql, SqlParameter[] sqlParams = null) where T : new() { return Execute<T>(db, sql, CommandType.Text, sqlParams); } private static int ExecuteNoQuery<T>(this EntityContext db, string sql, SqlParameter[] sqlParams) where T : new() { DbConnection connection = db.Database.GetDbConnection(); DbCommand cmd = connection.CreateCommand(); int result = 0; db.Database.OpenConnection(); cmd.CommandText = sql; cmd.CommandType = CommandType.Text; if (sqlParams != null) { cmd.Parameters.AddRange(sqlParams); } result = cmd.ExecuteNonQuery(); db.Database.CloseConnection(); return result; } private static IEnumerable<T> Execute<T>(this EntityContext db, string sql, CommandType type, SqlParameter[] sqlParams) where T : new() { DbConnection connection = db.Database.GetDbConnection(); DbCommand cmd = connection.CreateCommand(); db.Database.OpenConnection(); cmd.CommandText = sql; cmd.CommandType = type; if (sqlParams != null) { cmd.Parameters.AddRange(sqlParams); } DataTable dt = new DataTable(); using (DbDataReader reader = cmd.ExecuteReader()) { dt.Load(reader); } db.Database.CloseConnection(); return dt.ToCollection<T>(); } }
DataTable和集合的擴展this
public static class ExtendDataTable { public static DataTable ToDataTable<T>(this IEnumerable<T> data) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T)); var table = new DataTable(); foreach (PropertyDescriptor prop in properties) table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); foreach (T item in data) { DataRow row = table.NewRow(); foreach (PropertyDescriptor prop in properties) row[prop.Name] = prop.GetValue(item) ?? DBNull.Value; table.Rows.Add(row); } return table; } public static T ToEntity<T>(this DataTable dt) where T : new() { IEnumerable<T> entities = dt.ToCollection<T>(); return entities.FirstOrDefault(); } public static IEnumerable<T> ToCollection<T>(this DataTable dt) where T : new() { if (dt == null || dt.Rows.Count == 0) { return Enumerable.Empty<T>(); } IList<T> ts = new List<T>(); // 得到此模型的類型 Type type = typeof(T); string tempName = string.Empty; foreach (DataRow dr in dt.Rows) { T t = new T(); PropertyInfo[] propertys = t.GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { tempName = pi.Name; //檢查DataTable是否包含此列(列名==對象的屬性名) if (dt.Columns.Contains(tempName)) { // 判斷此屬性是否有Setter if (!pi.CanWrite) continue;//該屬性不可寫,直接跳出 object value = dr[tempName]; if (value != DBNull.Value) pi.SetValue(t, value, null); } } ts.Add(t); } return ts; } }
說明:上面的代碼是經過datareader的方式獲取數據集的,固然DbCommand 也支持異步的方式處理數據,我這邊沒有用到因此代碼也就沒有作擴展,我貌似沒有找到能夠經過dataadapter來填充dataset的方式獲取數據集的相關函數,若是有小夥伴知道在如何在EF Core中用dataadapter來填充dataset的方式獲取數據集,能夠把代碼貼評論區哦spa