大家好,我是考100分的小小码 ,祝大家学习进步,加薪顺利呀。今天说一说在ef中使用数据库上下文需要注意哪些事项_无法在源表中获得一组稳定的行,希望您对编程的造诣更进一步.
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Reflection; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; namespace ZR.OtnWebService.Models.OrderInfos { public static class DbContextExtensions { private static void CombineParams(ref DbCommand command, params object[] parameters) { if (parameters != null) { foreach (SqlParameter parameter in parameters) { if (!parameter.ParameterName.Contains("@")) parameter.ParameterName = $"@{parameter.ParameterName}"; command.Parameters.Add(parameter); } } } private static DbCommand CreateCommand(DatabaseFacade facade, string sql, out DbConnection dbConn, params object[] parameters) { DbConnection conn = facade.GetDbConnection(); dbConn = conn; conn.Open(); DbCommand cmd = conn.CreateCommand(); if (facade.IsMySql()) { cmd.CommandText = sql; CombineParams(ref cmd, parameters); } return cmd; } public static DataTable SqlQuery(this DatabaseFacade facade, string sql, params object[] parameters) { DbCommand cmd = CreateCommand(facade, sql, out DbConnection conn, parameters); DbDataReader reader = cmd.ExecuteReader(); DataTable dt = new DataTable(); dt.Load(reader); reader.Close(); conn.Close(); return dt; } public static IEnumerable<T> SqlQuery<T>(this DatabaseFacade facade, string sql, params object[] parameters) where T : class, new() { DataTable dt = SqlQuery(facade, sql, parameters); return dt.ToEnumerable<T>(); } public static IEnumerable<T> ToEnumerable<T>(this DataTable dt) where T : class, new() { PropertyInfo[] propertyInfos = typeof(T).GetProperties(); T[] ts = new T[dt.Rows.Count]; int i = 0; foreach (DataRow row in dt.Rows) { T 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); } ts[i] = t; i++; } return ts; } } }
代码100分
使用方法
代码100分DbContext.Database.SqlQuery<Model>($"SELECT * FROM Table").FirstOrDefault();
使用EFCore执行上下文不存在的SQL语句
原文地址:https://www.cnblogs.com/ShenJA/p/13335668.html
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
转载请注明出处: https://daima100.com/7288.html