排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术
分类:
EF
直接执行原生sql:
添加扩展方法:
public static class EntityFrameworkCoreExtensions { private static DbCommand CreateCommand(DatabaseFacade facade, string sql, out DbConnection connection, params object[] parameters) { var conn = facade.GetDbConnection(); connection = conn; conn.Open(); var cmd = conn.CreateCommand(); if (facade.IsSqlServer()) { cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); } return cmd; } public static DataTable SqlQuery(this DatabaseFacade facade, string sql, params object[] parameters) { var command = CreateCommand(facade, sql, out DbConnection conn, parameters); var reader = command.ExecuteReader(); var dt = new DataTable(); dt.Load(reader); reader.Close(); conn.Close(); return dt; } public static List<T> SqlQuery<T>(this DatabaseFacade facade, string sql, params object[] parameters) where T : class, new() { var dt = SqlQuery(facade, sql, parameters); return dt.ToList<T>(); } public static List<T> ToList<T>(this DataTable dt) where T : class, new() { var propertyInfos = typeof(T).GetProperties(); var list = new List<T>(); foreach (DataRow row in dt.Rows) { var t = new T(); foreach (PropertyInfo p in propertyInfos) { if (dt.Columns.IndexOf(p.Name) != -1 && row[p.Name] != DBNull.Value) p.SetValue(t, row[p.Name], null); } list.Add(t); } return list; } }
使用:
List<Users> ulist = se.Database.SqlQuery<Users>("select * from users where number=@number", new SqlParameter("number", "NS001")).ToList();
执行添加,删除,修改等操作
方法1:
int count =Database.ExecuteSqlRaw(sql,params);
方法2:
context.Database.ExecuteSqlInterpolated()
欢迎加群讨论技术,群:677373950(满了,可以加,但通过不了),2群:656732739
评价