.net 6 EF 中使用sql的小扩展

using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace Todo.Models
{
    public partial class myContext : DbContext
    {
        public List<T> ExceSQL<T>(string sql)
        {
            using (var command = Database.GetDbConnection().CreateCommand())
            {
                command.CommandText = sql;
                command.CommandType = CommandType.Text;
                Database.OpenConnection();
                List<T> ts = new List<T>();
                using (var result = command.ExecuteReader())
                {
                    T obj = default(T);
                    while (result.Read())
                    {
                        obj = Activator.CreateInstance<T>();
                        foreach (PropertyInfo prop in obj.GetType().GetProperties())
                        {
                            if (!object.Equals(result[prop.Name], DBNull.Value))
                            {
                                prop.SetValue(obj, result[prop.Name], null);
                            }
                        }
                        ts.Add(obj);
                    }
                }
                Database.CloseConnection();
                return ts;
            }
        }
    }
}
 
posted @ 2022-05-02 16:27  changsen-  阅读(199)  评论(0编辑  收藏  举报