ホームページ  >  記事  >  バックエンド開発  >  ASP.NETのSqlDataReaderで生成される動的ラムダ式の例の詳細な説明

ASP.NETのSqlDataReaderで生成される動的ラムダ式の例の詳細な説明

Y2J
Y2Jオリジナル
2017-04-27 10:12:091969ブラウズ

この記事では主に SqlDataReader で生成された動的ラムダ式を紹介しますので、必要な方は参考にしてください

前の記事では動的ラムダ式を使用して 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 &#39;ID&#39;,name &#39;Name&#39; 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 Extension メソッドを追加したかったのですが、ラムダ式を動的に生成する際にエラーが見つかったので、最初に現在の解決策を記録しました。

以上がASP.NETのSqlDataReaderで生成される動的ラムダ式の例の詳細な説明の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。