SqlDataReader Generates Dynamic Lambda Expressions

  • 2021-09-16 06:42:25
  • OfStack

The first flat uses dynamic lambda expressions to convert DataTable into entities, which is much faster than using reflection directly. The main reason is that the delegate is dynamically generated when the first line is converted.

Later transformations call delegates directly, which saves the performance loss caused by using reflection many times.

Today, the stream object SqlDataReader returned by SqlServer is processed, and the entity is transformed by dynamically generating Lambda expressions.

First version 1 code


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 Generate Entity 
  /// </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", " The current object is null Unable to build expression tree ");
   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>
  ///  Generate expression 
  /// </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", " The current object is null  Unable to convert to entity ");
   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>
  ///  Generate lambda Expression 
  /// </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", " The current object is invalid ");
   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();
  }
 }
}

On the basis of the previous article, the expansion method of SqlDataReader is added

The following code is used to call the


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; }
 }
}

At present, it can only deal with the objects returned by sqlserver. When dealing with other databases, it was originally intended to increase the expansion method of DbDataReader, but it was found that there was an error in dynamically generating lambda expressions, so the current

Record the plan.


Related articles: