zoukankan      html  css  js  c++  java
  • EF Core 拓展SqlQuery方法


    public static IEnumerable<T> SqlQuery<T>(this DatabaseFacade facade, string sql, params object[] parameters) where T : class, new() { DataTable dt = SqlQuery(facade, sql, parameters); return dt.ToEnumerable<T>(); } public static IEnumerable<T> ToEnumerable<T>(this DataTable dt) where T : class, new() { PropertyInfo[] propertyInfos = typeof(T).GetProperties(); T[] ts = new T[dt.Rows.Count]; int i = 0; foreach (DataRow row in dt.Rows) { T t = new T(); foreach (PropertyInfo p in propertyInfos) { if (dt.Columns.IndexOf(p.Name) != -1 && row[p.Name] != DBNull.Value) p.SetValue(t, row[p.Name], null); } ts[i] = t; i++; } return ts; } public static DataTable SqlQuery(this DatabaseFacade facade, string sql, params object[] parameters) { DbCommand cmd = CreateCommand(facade, sql, out DbConnection conn, parameters); DbDataReader reader = cmd.ExecuteReader(); DataTable dt = new DataTable(); dt.Load(reader); reader.Close(); conn.Close(); return dt; } private static DbCommand CreateCommand(DatabaseFacade facade, string sql, out DbConnection dbConn, params object[] parameters) { DbConnection conn = facade.GetDbConnection(); dbConn = conn; conn.Open(); DbCommand cmd = conn.CreateCommand(); if (facade.IsSqlServer()) { cmd.CommandText = sql; CombineParams(ref cmd, parameters); } return cmd; } private static void CombineParams(ref DbCommand command, params object[] parameters) { if (parameters != null) { foreach (SqlParameter parameter in parameters) { if (!parameter.ParameterName.Contains("@")) parameter.ParameterName = $"@{parameter.ParameterName}"; command.Parameters.Add(parameter); } } }

      

    使用

    this.context.Database.SqlQuery<GetFeedbackLawyer_ReturnModel>("sql").ToList();
    

      

  • 相关阅读:
    POJ 1631 Bridging signals
    POJ 1451 T9
    企业应用架构模式阅读笔记3
    论面向服务架构设计及其应用
    软件质量属性-可测试性
    企业应用架构模式阅读笔记2
    企业应用架构模式阅读笔记1
    QTP安装与破解
    Android studio打不开,双击没有反应,已解决
    hibernate框架的基本原理及实例
  • 原文地址:https://www.cnblogs.com/JoeyZJ/p/11819495.html
Copyright © 2011-2022 走看看