efcore调用函数_如何在EF Core 使用存储过程
使用EF Core框架能快速的幫助我們進行常規(guī)的數(shù)據(jù)處理和項目開發(fā),但是ORM雖然好用,但是在許多復雜邏輯的數(shù)據(jù)處理時,我個人還是偏向用SQL和存儲過程的方式去處理,但是研究了一下目前最新版本的EF Core(我用的是2.1)以及相關文檔,貌似沒有找到可以很好支持原始SQL開發(fā)的方案,于是就自己簡單的擴展了一下
首先說一下我查閱文檔找到已知的EF Core可以執(zhí)行SQL和存儲過程的兩個函數(shù)ExecuteSqlCommand()和FromSql()
1,ExecuteSqlCommand(),代碼中的EntityContext即為數(shù)據(jù)框架上下文對象,這種方法可以執(zhí)行sql或者存儲過程并且傳遞參數(shù),但是缺點就是函數(shù)的返回結果為int類型的受影響行數(shù),無法返回指定的數(shù)據(jù)集
private EntityContext context = null;publicValuesController(EntityContext _context)
{
context=_context;
}///
///測試代碼///
///
[HttpPost("Post")]public intPost()
{long uid = 4;int data = context.Database.ExecuteSqlCommand($"exec proc_test {uid}", uid);returndata;
}
2,FromSql()可以用來執(zhí)行帶參數(shù)的sql,這個函數(shù)的用法以及優(yōu)缺點可以看官方文檔的這篇文章
https://docs.microsoft.com/en-us/ef/core/querying/raw-sql
3,用DbCommand 簡單的擴展數(shù)據(jù)框架上下文對象,使其可以執(zhí)行存儲過程并返回你想要的數(shù)據(jù)類型
public static classExtendDBContext
{///
///執(zhí)行SQL返回受影響的行數(shù)///
public static int ExecSqlNoQuery(this EntityContext db, string sql, SqlParameter[] sqlParams = null) where T : new()
{return ExecuteNoQuery(db, sql, sqlParams);
}///
///執(zhí)行存儲過程返回IEnumerable數(shù)據(jù)集///
public static IEnumerable ExecProcReader(this EntityContext db, string sql, SqlParameter[] sqlParams = null) where T : new()
{return Execute(db, sql, CommandType.StoredProcedure, sqlParams);
}///
///執(zhí)行sql返回IEnumerable數(shù)據(jù)集///
public static IEnumerable ExecSqlReader(this EntityContext db, string sql, SqlParameter[] sqlParams = null) where T : new()
{return Execute(db, sql, CommandType.Text, sqlParams);
}private static int ExecuteNoQuery(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();returnresult;
}private static IEnumerable Execute(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= newDataTable();using (DbDataReader reader =cmd.ExecuteReader())
{
dt.Load(reader);
}
db.Database.CloseConnection();return dt.ToCollection();
}
}
DataTable和集合的擴展
public static classExtendDataTable
{public static DataTable ToDataTable(this IEnumerabledata)
{
PropertyDescriptorCollection properties= TypeDescriptor.GetProperties(typeof(T));var table = newDataTable();foreach (PropertyDescriptor prop inproperties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType)??prop.PropertyType);foreach (T item indata)
{
DataRow row=table.NewRow();foreach (PropertyDescriptor prop inproperties)
row[prop.Name]= prop.GetValue(item) ??DBNull.Value;
table.Rows.Add(row);
}returntable;
}public static T ToEntity(this DataTable dt) where T : new()
{
IEnumerable entities = dt.ToCollection();returnentities.FirstOrDefault();
}public static IEnumerable ToCollection(this DataTable dt) where T : new()
{if (dt == null || dt.Rows.Count == 0)
{return Enumerable.Empty();
}
IList ts = new List();//獲得此模型的類型
Type type = typeof(T);string tempName = string.Empty;foreach (DataRow dr indt.Rows)
{
T t= newT();
PropertyInfo[] propertys=t.GetType().GetProperties();foreach (PropertyInfo pi inpropertys)
{
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);
}returnts;
}
}
說明:上面的代碼是通過datareader的方式獲取數(shù)據(jù)集的,當然DbCommand 也支持異步的方式處理數(shù)據(jù),我這邊沒有用到所以代碼也就沒有做擴展,我貌似沒有找到可以通過dataadapter來填充dataset的方式獲取數(shù)據(jù)集的相關函數(shù),如果有小伙伴知道在如何在EF Core中用dataadapter來填充dataset的方式獲取數(shù)據(jù)集,可以把代碼貼評論區(qū)哦
總結
以上是生活随笔為你收集整理的efcore调用函数_如何在EF Core 使用存储过程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: copyproperties爆红_Bea
- 下一篇: ie网络集合代理无法启动_网络故障诊断7