using System; using System.Collections.Generic; using System.Data.Common; using System.Reflection; using Microsoft.EntityFrameworkCore; namespace Hncore.Infrastructure.EF { public static class Sql { /// /// 执行Reader /// /// /// /// public static void Reader(this DbContext dbContext, string sql, Action action) { var conn = dbContext.Database.GetDbConnection(); try { conn.Open(); using (var command = conn.CreateCommand()) { string query = sql; command.CommandText = query; using (DbDataReader reader = command.ExecuteReader()) { if (reader.HasRows) { while (reader.Read()) { action(reader); } } } } } finally { conn.Close(); } } /// /// 执行Query /// /// /// /// /// public static List SqlQuery(this DbContext dbContext, string sql) { List list = new List(); var conn = dbContext.Database.GetDbConnection(); try { conn.Open(); using (var command = conn.CreateCommand()) { string query = sql; command.CommandText = query; using (DbDataReader reader = command.ExecuteReader()) { if (reader.HasRows) { list = reader.ReaderToList(); } } } } finally { conn.Close(); } return list; } /// /// 执行Sql命令 /// /// /// /// public static int ExecuteSql(this DbContext dbContext, string sql) { var conn = dbContext.Database.GetDbConnection(); int rowAffected = 0; try { conn.Open(); using (var command = conn.CreateCommand()) { command.CommandText = sql; rowAffected = command.ExecuteNonQuery(); } } finally { conn.Close(); } return rowAffected; } /// /// DataReader转泛型 /// /// 传入的实体类 /// DataReader对象 /// public static List ReaderToList(this DbDataReader objReader) { using (objReader) { List list = new List(); //获取传入的数据类型 Type modelType = typeof(T); //遍历DataReader对象 while (objReader.Read()) { //使用与指定参数匹配最高的构造函数,来创建指定类型的实例 T model = Activator.CreateInstance(); for (int i = 0; i < objReader.FieldCount; i++) { //判断字段值是否为空或不存在的值 if (!IsNullOrDBNull(objReader[i])) { //匹配字段名 PropertyInfo pi = modelType.GetProperty(objReader.GetName(i), BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (pi != null) { //绑定实体对象中同名的字段 pi.SetValue(model, CheckType(objReader[i], pi.PropertyType), null); } } } list.Add(model); } return list; } } /// /// 判断指定对象是否是有效值 /// /// /// private static bool IsNullOrDBNull(object obj) { return (obj == null || (obj is DBNull)) ? true : false; } /// /// 对可空类型进行判断转换 /// /// DataReader字段的值 /// 该字段的类型 /// private static object CheckType(object value, Type conversionType) { if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { if (value == null) return null; System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType); conversionType = nullableConverter.UnderlyingType; } if (typeof(System.Enum).IsAssignableFrom(conversionType)) { return Enum.Parse(conversionType, value.ToString()); } return Convert.ChangeType(value, conversionType); } } }