SqlDataReader生成動(dòng)態(tài)Lambda表達(dá)式
上一扁使用動(dòng)態(tài)lambda表達(dá)式來將DataTable轉(zhuǎn)換成實(shí)體,比直接用反射快了不少。主要是首行轉(zhuǎn)換的時(shí)候動(dòng)態(tài)生成了委托。
后面的轉(zhuǎn)換都是直接調(diào)用委托,省去了多次用反射帶來的性能損失。
今天在對(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無法生成表達(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 無法轉(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ì)象無效"); 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ù)庫本來是想增加 DbDataReader 的擴(kuò)展方法,但發(fā)現(xiàn)動(dòng)態(tài)生成lambda表達(dá)式的地方出錯(cuò),所以先將現(xiàn)在的
方案記錄下來。
相關(guān)文章
asp.net 中國身份證號(hào)碼驗(yàn)證代碼 非正則
asp.net 中國身份證號(hào)碼驗(yàn)證,需要的朋友可以參考下。2009-11-11asp.net下實(shí)現(xiàn)輸入數(shù)字的冒泡排序
.net下實(shí)現(xiàn)輸入數(shù)字的冒泡排序2010-03-03ASP.NET實(shí)現(xiàn)進(jìn)度條效果
這篇文章主要為大家詳細(xì)介紹了ASP.NET實(shí)現(xiàn)簡(jiǎn)單的進(jìn)度條效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06.NET醫(yī)院公眾號(hào)系統(tǒng)線程CPU雙高問題分析
這篇文章主要介紹了.NET醫(yī)院公眾號(hào)系統(tǒng) 線程CPU雙高分析,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04Asp.Net Core控制器如何接收原始請(qǐng)求正文內(nèi)容詳解
這篇文章主要給大家介紹了關(guān)于Asp.Net Core控制器如何接收原始請(qǐng)求正文內(nèi)容的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-09-09ASP.NET Core使用SkiaSharp實(shí)現(xiàn)驗(yàn)證碼的示例代碼
本篇文章主要介紹了ASP.NET Core使用SkiaSharp實(shí)現(xiàn)驗(yàn)證碼的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-12-12asp.net基于Web Service實(shí)現(xiàn)遠(yuǎn)程上傳圖片的方法
這篇文章主要介紹了asp.net基于Web Service實(shí)現(xiàn)遠(yuǎn)程上傳圖片的方法,涉及asp.net調(diào)用Web Service的文件流操作與文件傳輸實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-12-12