SqlDataReader如何生成動(dòng)態(tài)Lambda表達(dá)式-創(chuàng)新互聯(lián)

這篇文章主要介紹SqlDataReader如何生成動(dòng)態(tài)Lambda表達(dá)式,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

成都創(chuàng)新互聯(lián)專注于網(wǎng)站建設(shè)|成都企業(yè)網(wǎng)站維護(hù)|優(yōu)化|托管以及網(wǎng)絡(luò)推廣,積累了大量的網(wǎng)站設(shè)計(jì)與制作經(jīng)驗(yàn),為許多企業(yè)提供了網(wǎng)站定制設(shè)計(jì)服務(wù),案例作品覆蓋服務(wù)器托管等行業(yè)。能根據(jù)企業(yè)所處的行業(yè)與銷售的產(chǎn)品,結(jié)合品牌形象的塑造,量身定制品質(zhì)網(wǎng)站。

今天在對(duì)SqlServer返回的流對(duì)象 SqlDataReader 進(jìn)行處理,也采用動(dòng)態(tài)生成Lambda表達(dá)式的方式轉(zhuǎn)換實(shí)體。

先上一版代碼

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Demo1
{
 public static class EntityConverter
 {
  #region
  /// <summary>
  /// DataTable生成實(shí)體
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="dataTable"></param>
  /// <returns></returns>
  public static List<T> ToList<T>(this DataTable dataTable) where T : class, new()
  {
   if (dataTable == null || dataTable.Rows.Count <= 0) throw new ArgumentNullException("dataTable", "當(dāng)前對(duì)象為null無(wú)法生成表達(dá)式樹");
   Func<DataRow, T> func = dataTable.Rows[0].ToExpression<T>();
   List<T> collection = new List<T>(dataTable.Rows.Count);
   foreach (DataRow dr in dataTable.Rows)
   {
    collection.Add(func(dr));
   }
   return collection;
  }
  /// <summary>
  /// 生成表達(dá)式
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="dataRow"></param>
  /// <returns></returns>
  public static Func<DataRow, T> ToExpression<T>(this DataRow dataRow) where T : class, new()
  {
   if (dataRow == null) throw new ArgumentNullException("dataRow", "當(dāng)前對(duì)象為null 無(wú)法轉(zhuǎn)換成實(shí)體");
   ParameterExpression parameter = Expression.Parameter(typeof(DataRow), "dr");
   List<MemberBinding> binds = new List<MemberBinding>();
   for (int i = 0; i < dataRow.ItemArray.Length; i++)
   {
    String colName = dataRow.Table.Columns[i].ColumnName;
    PropertyInfo pInfo = typeof(T).GetProperty(colName);
    if (pInfo == null || !pInfo.CanWrite) continue;
    MethodInfo mInfo = typeof(DataRowExtensions).GetMethod("Field", new Type[] { typeof(DataRow), typeof(String) }).MakeGenericMethod(pInfo.PropertyType);
    MethodCallExpression call = Expression.Call(mInfo, parameter, Expression.Constant(colName, typeof(String)));
    MemberAssignment bind = Expression.Bind(pInfo, call);
    binds.Add(bind);
   }
   MemberInitExpression init = Expression.MemberInit(Expression.New(typeof(T)), binds.ToArray());
   return Expression.Lambda<Func<DataRow, T>>(init, parameter).Compile();
  }
  #endregion
  /// <summary>
  /// 生成lambda表達(dá)式
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="reader"></param>
  /// <returns></returns>
  public static Func<SqlDataReader, T> ToExpression<T>(this SqlDataReader reader) where T : class, new()
  {
   if (reader == null || reader.IsClosed || !reader.HasRows) throw new ArgumentException("reader", "當(dāng)前對(duì)象無(wú)效");
   ParameterExpression parameter = Expression.Parameter(typeof(SqlDataReader), "reader");
   List<MemberBinding> binds = new List<MemberBinding>();
   for (int i = 0; i < reader.FieldCount; i++)
   {
    String colName = reader.GetName(i);
    PropertyInfo pInfo = typeof(T).GetProperty(colName);
    if (pInfo == null || !pInfo.CanWrite) continue;
    MethodInfo mInfo = reader.GetType().GetMethod("GetFieldValue").MakeGenericMethod(pInfo.PropertyType);
    MethodCallExpression call = Expression.Call(parameter, mInfo, Expression.Constant(i));
    MemberAssignment bind = Expression.Bind(pInfo, call);
    binds.Add(bind);
   }
   MemberInitExpression init = Expression.MemberInit(Expression.New(typeof(T)), binds.ToArray());
   return Expression.Lambda<Func<SqlDataReader, T>>(init, parameter).Compile();
  }
 }
}

在上一篇的基礎(chǔ)上增加了 SqlDataReader 的擴(kuò)展方法

以下代碼是調(diào)用

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Demo1
{
 class Program
 {
  static void Main(string[] args)
  {
   String conString = "Data Source=.; Initial Catalog=master; Integrated Security=true;";
   Func<SqlDataReader, Usr> func = null;
   List<Usr> usrs = new List<Usr>();
   using (SqlDataReader reader = GetReader(conString, "select object_id 'ID',name 'Name' from sys.objects", CommandType.Text, null))
   {
    while (reader.Read())
    {
     if (func == null)
     {
      func = reader.ToExpression<Usr>();
     }
     Usr usr = func(reader);
     usrs.Add(usr);
    }
   }
   usrs.Clear();
   Console.ReadKey();
  }
  public static SqlDataReader GetReader(String conString, String sql, CommandType type, params SqlParameter[] pms)
  {
   SqlConnection conn = new SqlConnection(conString);
   SqlCommand cmd = new SqlCommand(sql, conn);
   cmd.CommandType = type;
   if (pms != null && pms.Count() > 0)
   {
    cmd.Parameters.AddRange(pms);
   }
   conn.Open();
   return cmd.ExecuteReader(CommandBehavior.CloseConnection);
  }
 }
 class Usr
 {
  public Int32 ID { get; set; }
  public String Name { get; set; }
 }
}

目前只能處理sqlserver返回的對(duì)象,處理其它數(shù)據(jù)庫(kù)本來(lái)是想增加 DbDataReader 的擴(kuò)展方法,但發(fā)現(xiàn)動(dòng)態(tài)生成lambda表達(dá)式的地方出錯(cuò),所以先將現(xiàn)在的。

以上是“SqlDataReader如何生成動(dòng)態(tài)Lambda表達(dá)式”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

網(wǎng)站題目:SqlDataReader如何生成動(dòng)態(tài)Lambda表達(dá)式-創(chuàng)新互聯(lián)
鏈接分享:http://muchs.cn/article10/ejogo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)網(wǎng)站制作、品牌網(wǎng)站設(shè)計(jì)、網(wǎng)站內(nèi)鏈響應(yīng)式網(wǎng)站、標(biāo)簽優(yōu)化、域名注冊(cè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)公司