使用Asp.Net Core MVC 开发项目实践[第三篇:基于EF Core的扩展]
上篇我们说到了EFCore的基础使用,这篇我们将讲解下基于EFCore的扩展.
我们在Mango.Framework.EFCore类库项目中创建一个类名EFExtended的扩展类,并且引入相关的命名空间
using System; using System.Reflection; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using Microsoft.EntityFrameworkCore; using System.Linq; using System.Linq.Expressions; namespace Mango.Framework.EFCore { public static class EFExtended {} }
第一个扩展:基于传统DataTable(这个在2.0中才开始有)的返回
#region 查询返回DataTable的扩展 /// /// ///自定义SQL语句 ///参数 /// public static DataTable QueryDataTable(this DbContext context, string sql, params SqlParameter[] parameters) { DbConnection connection = null; DbCommand command = null; try { connection = context.Database.GetDbConnection(); if (connection.State == ConnectionState.Closed) { connection.Open(); } command = connection.CreateCommand(); command.CommandText = sql; command.Parameters.AddRange(parameters); DbDataReader reader = command.ExecuteReader(); var result= FillDataTable(reader); //释放连接资源 command.Dispose(); connection.Close(); // return result; } catch (Exception ex) { throw ex; } finally { //释放连接资源 if (command != null) { command.Dispose(); } if (connection != null) { connection.Close(); } } } /// /// /// private static DataTable FillDataTable(DbDataReader reader) { bool defined = false; DataTable table = new DataTable(); while (reader.Read()) { object[] values = new object[reader.FieldCount]; //插入列信息 if (!defined) { for (int i = 0; i < reader.FieldCount; i++) { DataColumn column = new DataColumn() { ColumnName = reader.GetName(i), DataType = reader.GetFieldType(i) }; table.Columns.Add(column); } defined = true; } //插入数据 reader.GetValues(values); DataRow dataRow = table.NewRow(); for (int i = 0; i < values.Length; i++) { dataRow[i] = values[i]; } table.Rows.Add(dataRow); } return table; } #endregion
就是通过DbCommand类执行SQL语句返回DbDataReader的数据集合,将返回的数据集合填充到DataTable实例中去.
第二个扩展:基于SQL语句的查询返回指定的集合对象
using System; using System.Collections.Generic; using System.Reflection; using System.ComponentModel; namespace Mango.Framework.EFCore { public class DbIdentity { /// /// /// /// internal static object Change(object value, Type type) { if (type.IsGenericParameter) { if (type.IsGenericParameter && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { if (value == null) { return null; } NullableConverter nullableConverter = new NullableConverter(type); value = Convert.ChangeType(value, type); } } return value; } } }