ASP.NET中SqlDataReader產生動態Lambda運算式的執行個體詳解

來源:互聯網
上載者:User
這篇文章主要介紹了SqlDataReader產生動態Lambda運算式,需要的朋友可以參考下

上一扁使用動態lambda運算式來將DataTable轉換成實體,比直接用反射快了不少。主要是首行轉換的時候動態產生了委託。

後面的轉換都是直接調用委託,省去了多次用反射帶來的效能損失。

今天在對SqlServer返回的流對象 SqlDataReader 進行處理,也採用動態產生Lambda運算式的方式轉換實體。

先上一版代碼

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產生實體  /// </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", "當前對象為null無法產生運算式樹狀架構");   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>  /// 產生運算式  /// </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", "當前對象為null 無法轉換成實體");   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運算式  /// </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", "當前對象無效");   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();  } }}

在上一篇的基礎上增加了 SqlDataReader 的擴充方法

以下代碼是調用

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返回的對象,處理其它資料庫本來是想增加 DbDataReader 的擴充方法,但發現動態產生lambda運算式的地方出錯,所以先將現在的

方案記錄下來。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.