SqlDataReader生成動態(tài)Lambda表達式
上一扁使用動態(tài)lambda表達式來將DataTable轉(zhuǎn)換成實體,比直接用反射快了不少。主要是首行轉(zhuǎn)換的時候動態(tài)生成了委托。
后面的轉(zhuǎn)換都是直接調(diào)用委托,省去了多次用反射帶來的性能損失。
今天在對SqlServer返回的流對象 SqlDataReader 進行處理,也采用動態(tài)生成Lambda表達式的方式轉(zhuǎn)換實體。
先上一版代碼
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 無法轉(zhuǎn)換成實體");
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();
}
}
}
在上一篇的基礎(chǔ)上增加了 SqlDataReader 的擴展方法
以下代碼是調(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返回的對象,處理其它數(shù)據(jù)庫本來是想增加 DbDataReader 的擴展方法,但發(fā)現(xiàn)動態(tài)生成lambda表達式的地方出錯,所以先將現(xiàn)在的
方案記錄下來。
相關(guān)文章
.NET獲取枚舉DescriptionAttribute描述信息性能改進的多種方法
這篇文章主要介紹了.NET獲取枚舉DescriptionAttribute描述信息性能改進的多種方法 的相關(guān)資料,需要的朋友可以參考下2016-01-01
swagger上傳文件并支持jwt認證的實現(xiàn)方法
今天通過本文給大家分享swagger上傳文件并支持jwt認證的實現(xiàn)方法,文中提到了安裝方法及實現(xiàn)代碼,感興趣的朋友跟隨腳本之家小編一起學習吧2018-05-05
ASP.Net MVC_DotNetZip簡單使用方法,解決文件壓縮的問題
下面小編就為大家?guī)硪黄狝SP.Net MVC_DotNetZip簡單使用方法,解決文件壓縮的問題。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-06-06
Asp.Net實現(xiàn)FORM認證的一些使用技巧(必看篇)
下面小編就為大家?guī)硪黄狝sp.Net實現(xiàn)FORM認證的一些使用技巧(必看篇)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08
詳解.NET Core使用Quartz執(zhí)行調(diào)度任務進階
這篇文章主要介紹了.NET Core使用Quartz執(zhí)行調(diào)度任務進階,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-04-04
ASP.NET?使用?Dispose?釋放資源的四種方法詳細介紹
本篇文章主要介紹了ASP.NET?使用?Dispose?釋放資源的四種方法,有興趣的同學可以來看看,喜歡的話記得收藏一下哦,方便下次瀏覽觀看2021-11-11
限制CheckBoxList控件只能單選實現(xiàn)代碼及演示動畫
開發(fā)要求,原本對CheckBoxList控件是用來讓用戶多選的。但現(xiàn)在特殊要求,這個CheckBoxList控件限制只能單選,很多新手朋友可能不知從何下手,為此本文的出現(xiàn)時有必要的了,有需要的朋友可以了解此文2013-01-01

