You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.4 KiB
C#

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace Khd.Core.EntityFramework
{
public static class DbContextExtensions
{
//public static List<T> ExecuteSqlQuery<T>(this DbContext dbContext, string sqlQuery) where T : class
//{
// using var command = dbContext.Database.GetDbConnection().CreateCommand();
// command.CommandText = sqlQuery;
// command.CommandType = CommandType.Text;
// dbContext.Database.OpenConnection();
// using var reader = command.ExecuteReader();
// var result = new List<T>();
// while (reader.Read())
// {
// var entity = Activator.CreateInstance<T>();
// foreach (var prop in typeof(T).GetProperties())
// {
// var value = reader[prop.Name];
// if (value != DBNull.Value)
// {
// prop.SetValue(entity, value);
// }
// }
// result.Add(entity);
// }
// return result;
//}
public static List<T> ExecuteSqlQuery<T>(this DbContext dbContext, string sqlQuery) where T : class, new()
{
using var command = dbContext.Database.GetDbConnection().CreateCommand();
command.CommandText = sqlQuery;
command.CommandType = CommandType.Text;
dbContext.Database.OpenConnection();
using var reader = command.ExecuteReader();
var result = new List<T>();
var columnNames = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToList();
while (reader.Read())
{
var entity = new T();
var properties = typeof(T).GetProperties();
foreach (var prop in properties)
{
var propName = prop.Name;
if (!columnNames.Contains(propName))
continue;
var value = reader[propName];
if (value != DBNull.Value)
{
prop.SetValue(entity, value);
}
}
result.Add(entity);
}
return result;
}
}
}