上一扁使用動(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í)體。
先上一版代碼
1 using System; 2 using System.Collections.Generic; 3 using System.Data; 4 using System.Data.Common; 5 using System.Data.SqlClient; 6 using System.Linq; 7 using System.Linq.Expressions; 8 using System.Reflection; 9 using System.Text;10 using System.Threading.Tasks;11 12 namespace Demo113 {14 public static class EntityConverter15 {16 #region17 /// <summary>18 /// DataTable生成實(shí)體19 /// </summary>20 /// <typeparam name="T"></typeparam>21 /// <param name="dataTable"></param>22 /// <returns></returns>23 public static List<T> ToList<T>(this DataTable dataTable) where T : class, new()24 {25 if (dataTable == null || dataTable.Rows.Count <= 0) throw new ArgumentNullException("dataTable", "當(dāng)前對(duì)象為null無法生成表達(dá)式樹");26 Func<DataRow, T> func = dataTable.Rows[0].ToExpression<T>();27 List<T> collection = new List<T>(dataTable.Rows.Count);28 foreach (DataRow dr in dataTable.Rows)29 {30 collection.Add(func(dr));31 }32 return collection;33 }34 35 36 /// <summary>37 /// 生成表達(dá)式38 /// </summary>39 /// <typeparam name="T"></typeparam>40 /// <param name="dataRow"></param>41 /// <returns></returns>42 public static Func<DataRow, T> ToExpression<T>(this DataRow dataRow) where T : class, new()43 {44 if (dataRow == null) throw new ArgumentNullException("dataRow", "當(dāng)前對(duì)象為null 無法轉(zhuǎn)換成實(shí)體");45 ParameterExpression parameter = Expression.Parameter(typeof(DataRow), "dr");46 List<MemberBinding> binds = new List<MemberBinding>();47 for (int i = 0; i < dataRow.ItemArray.Length; i++)48 {49 String colName = dataRow.Table.Columns[i].ColumnName;50 PropertyInfo pInfo = typeof(T).GetProperty(colName);51 if (pInfo == null || !pInfo.CanWrite) continue;52 MethodInfo mInfo = typeof(DataRowExtensions).GetMethod("Field", new Type[] { typeof(DataRow), typeof(String) }).MakeGenericMethod(pInfo.PropertyType);53 MethodCallExpression call = Expression.Call(mInfo, parameter, Expression.Constant(colName, typeof(String)));54 MemberAssignment bind = Expression.Bind(pInfo, call);55 binds.Add(bind);56 }57 MemberInitExpression init = Expression.MemberInit(Expression.New(typeof(T)), binds.ToArray());58 return Expression.Lambda<Func<DataRow, T>>(init, parameter).Compile();59 }60 #endregion61 /// <summary>62 /// 生成lambda表達(dá)式63 /// </summary>64 /// <typeparam name="T"></typeparam>65 /// <param name="reader"></param>66 /// <returns></returns>67 public static Func<SqlDataReader, T> ToExpression<T>(this SqlDataReader reader) where T : class, new()68 {69 if (reader == null || reader.IsClosed || !reader.HasRows) throw new ArgumentException("reader", "當(dāng)前對(duì)象無效");70 ParameterExpression parameter = Expression.Parameter(typeof(SqlDataReader), "reader");71 List<MemberBinding> binds = new List<MemberBinding>();72 for (int i = 0; i < reader.FieldCount; i++)73 {74 String colName = reader.GetName(i);75 PropertyInfo pInfo = typeof(T).GetProperty(colName);76 if (pInfo == null || !pInfo.CanWrite) continue;77 MethodInfo mInfo = reader.GetType().GetMethod("GetFieldValue").MakeGenericMethod(pInfo.PropertyType);78 MethodCallExpression call = Expression.Call(parameter, mInfo, Expression.Constant(i));79 MemberAssignment bind = Expression.Bind(pInfo, call);80 binds.Add(bind);81 }82 MemberInitExpression init = Expression.MemberInit(Expression.New(typeof(T)), binds.ToArray());83 return Expression.Lambda<Func<SqlDataReader, T>>(init, parameter).Compile();84 }85 86 }87 }
在上一篇的基礎(chǔ)上增加了 SqlDataReader 的擴(kuò)展方法
以下代碼是調(diào)用
1 using System; 2 using System.Collections.Generic; 3 using System.Data; 4 using System.Data.Common; 5 using System.Data.SqlClient; 6 using System.Diagnostics; 7 using System.Linq; 8 using System.Reflection; 9 using System.Text;10 using System.Threading.Tasks;11 12 namespace Demo113 {14 class Program15 {16 static void Main(string[] args)17 {18 String conString = "Data Source=.; Initial Catalog=master; Integrated Security=true;";19 Func<SqlDataReader, Usr> func = null;20 List<Usr> usrs = new List<Usr>();21 using (SqlDataReader reader = GetReader(conString, "select object_id 'ID',name 'Name' from sys.objects", CommandType.Text, null))22 {23 while (reader.Read())24 {25 if (func == null)26 {27 func = reader.ToExpression<Usr>();28 }29 Usr usr = func(reader);30 usrs.Add(usr);31 }32 }33 usrs.Clear();34 Console.ReadKey();35 }36 37 public static SqlDataReader GetReader(String conString, String sql, CommandType type, params SqlParameter[] pms)38 {39 SqlConnection conn = new SqlConnection(conString);40 SqlCommand cmd = new SqlCommand(sql, conn);41 cmd.CommandType = type;42 if (pms != null && pms.Count() > 0)43 {44 cmd.Parameters.AddRange(pms);45 }46 conn.Open();47 return cmd.ExecuteReader(CommandBehavior.CloseConnection);48 }49 }50 class Usr51 {52 public Int32 ID { get; set; }53 public String Name { get; set; }54 }55 56 57 }
目前只能處理sqlserver返回的對(duì)象,處理其它數(shù)據(jù)庫本來是想增加 DbDataReader 的擴(kuò)展方法,但發(fā)現(xiàn)動(dòng)態(tài)生成lambda表達(dá)式的地方出錯(cuò),所以先將現(xiàn)在的
方案記錄下來。
文中如果有不清楚或者有問題的地方請(qǐng)園友指出。謝謝。
原創(chuàng)作品,轉(zhuǎn)載請(qǐng)注明出處:http://www.cnblogs.com/lclblog/p/6711292.html
http://www.cnblogs.com/lclblog/p/6711292.html