using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Reflection;
namespace Hncore.Infrastructure.Extension
{
///
/// EF上下文对象扩展类
///
///
public static class DbContextExtension
{
///
/// 执行SQL返回受影响的行数
///
public static int ExecSqlNoQuery(this DbContext db, string sql, DbParameter[] sqlParams = null)
{
return ExecuteNoQuery(db, sql, sqlParams);
}
///
/// 执行存储过程返回IEnumerable数据集
///
public static IEnumerable ExecProcQuery(this DbContext db, string sql, DbParameter[] sqlParams = null) where T : new()
{
return Execute(db, sql, CommandType.StoredProcedure, sqlParams);
}
///
/// 执行存储过程返回IEnumerable数据集
///
public static DataSet ExecProcDataSet(this DbContext db, string sql, DbParameter[] sqlParams = null)
{
return ExecuteDataSet(db, sql, CommandType.StoredProcedure, sqlParams);
}
///
/// 执行sql返回IEnumerable数据集
///
public static IEnumerable ExecSqlQuery(this DbContext db, string sql, DbParameter[] sqlParams = null) where T : new()
{
return Execute(db, sql, CommandType.Text, sqlParams);
}
///
/// 执行SQL并返回受影响的行数
///
///
///
///
///
private static int ExecuteNoQuery(this DbContext db, string sql, DbParameter[] sqlParams)
{
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();
return result;
}
///
/// 执行SQL,返回查询结果
///
///
///
///
///
///
///
private static IEnumerable Execute(this DbContext db, string sql, CommandType type, DbParameter[] sqlParams) where T : new()
{
DbConnection connection = db.Database.GetDbConnection();
DbCommand cmd = connection.CreateCommand();
DataTable dt = new DataTable();
try
{
db.Database.OpenConnection();
cmd.CommandText = sql;
cmd.CommandType = type;
if (sqlParams != null)
{
cmd.Parameters.AddRange(sqlParams);
}
using (DbDataReader reader = cmd.ExecuteReader())
{
dt.Load(reader);
}
}
finally
{
db.Database.CloseConnection();
}
return dt.ToCollection();
}
///
/// 执行SQL,返回查询结果
///
///
///
///
///
///
///
private static DataSet ExecuteDataSet(this DbContext db, string sql, CommandType type, DbParameter[] sqlParams)
{
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);
}
DataSet ds = new DataSet();
using (DbDataReader reader = cmd.ExecuteReader())
{
ds.Load(reader,LoadOption.PreserveChanges,"data","info");
}
db.Database.CloseConnection();
return ds;
}
}
///
/// DataTable扩展类
///
///
public static class ExtendDataTable
{
///
/// 将对象转换成DataTable
///
/// 源对象类型
/// 源对象列表
/// 转换后的DataTable
///
public static DataTable ToDataTable(this IEnumerable data)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
var table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
///
/// 将DataTable首行转换成目标对象
///
/// 目标对象类型
/// 源DataTable对象
/// 转换后的目标对象
///
public static T ToEntity(this DataTable dt) where T : new()
{
IEnumerable entities = dt.ToCollection();
return entities.FirstOrDefault();
}
///
/// 将DataTable转换成目标对象列表
///
/// 目标对象类型
/// 源DataTable对象
/// 转换后的目标对象列表
///
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 in dt.Rows)
{
T t = new T();
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;
//检查DataTable是否包含此列(列名==对象的属性名)
if (dt.Columns.Contains(tempName))
{
// 判断此属性是否有Setter
if (!pi.CanWrite) continue;//该属性不可写,直接跳出
object value = dr[tempName];
if (value != DBNull.Value)
{
if (!pi.PropertyType.IsGenericType)
{
value = Convert.ChangeType(value, pi.PropertyType);
pi.SetValue(t, value);
}
else {
Type genericTypeDefinition = pi.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
value = Convert.ChangeType(value, Nullable.GetUnderlyingType(pi.PropertyType));
pi.SetValue(t, value);
}
}
}
}
}
ts.Add(t);
}
return ts;
}
}
}