生成动态Lambda表达式1
SqlDataReader生成动态Lambda表达式
上一扁使用动态lambda表达式来将DataTable转换成实体,比直接用反射快了不少。主要是首行转换的时候动态生成了委托。
后面的转换都是直接调用委托,省去了多次用反射带来的性能损失。
今天在对SqlServer返回的流对象 SqlDataReader 进行处理,也采用动态生成Lambda表达式的方式转换实体。
先上一版代码

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 Demo1
13 {
14 public static class EntityConverter
15 {
16 #region
17 /// <summary>
18 /// DataTable生成实体
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", "当前对象为null无法生成表达式树");
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 /// 生成表达式
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", "当前对象为null 无法转换成实体");
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 #endregion
61 /// <summary>
62 /// 生成lambda表达式
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", "当前对象无效");
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 }

在上一篇的基础上增加了 SqlDataReader 的扩展方法
以下代码是调用

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 Demo1
13 {
14 class Program
15 {
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 Usr
51 {
52 public Int32 ID { get; set; }
53 public String Name { get; set; }
54 }
55
56
57 }

目前只能处理sqlserver返回的对象,处理其它数据库本来是想增加 DbDataReader 的扩展方法,但发现动态生成lambda表达式的地方出错,所以先将现在的
生成动态Lambda表达式1的更多相关文章
- SqlDataReader生成动态Lambda表达式
上一扁使用动态lambda表达式来将DataTable转换成实体,比直接用反射快了不少.主要是首行转换的时候动态生成了委托. 后面的转换都是直接调用委托,省去了多次用反射带来的性能损失. 今天在对Sq ...
- 动态生成C# Lambda表达式
转载:http://www.educity.cn/develop/1407905.html,并整理! 对于C# Lambda的理解我们在之前的文章中已经讲述过了,那么作为Delegate的进化使用,为 ...
- C# 构建动态Lambda表达式
做CURD开发的过程中,通常都会需要GetList,然而查询条件是一个可能变化的需求,如何从容对应需求变化呢? 首先,我们来设计一个套路,尝试以最小的工作量完成一次查询条件的需求变更 1.UI收集查询 ...
- EntityFramework使用动态Lambda表达式筛选数据
public static class PredicateBuilder { public static Expression<Func<T, bool>> True<T ...
- 动态LINQ(Lambda表达式)构建
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; us ...
- C# 动态构建表达式树(一)—— 构建 Where 的 Lambda 表达式
C# 动态构建表达式树(一)-- 构建 Where 的 Lambda 表达式 前言 记得之前同事在做筛选功能的时候提出过一个问题:如果用户传入的条件数量不确定,条件的内容也不确定(大于.小于和等于), ...
- Lambda表达式详解
前言 1.天真热,程序员活着不易,星期天,也要顶着火辣辣的太阳,总结这些东西. 2.夸夸lambda吧:简化了匿名委托的使用,让你让代码更加简洁,优雅.据说它是微软自c#1.0后新增的最重要的功能之一 ...
- lambda表达式-转载
来源:http://www.cnblogs.com/knowledgesea/p/3163725.html 前言 1.天真热,程序员活着不易,星期天,也要顶着火辣辣的太阳,总结这些东西. 2.夸夸 ...
- C# lambda表达式(简单易懂)
前言 1.天真热,程序员活着不易,星期天,也要顶着火辣辣的太阳,总结这些东西. 2.夸夸lambda吧:简化了匿名委托的使用,让你让代码更加简洁,优雅.据说它是微软自c#1.0后新增的最重要的功能之一 ...
随机推荐
- 把java程序打包成.exe
准备工作:将可执行的jar包跟资源跟第三方包都放到一个目录下. 能够将jre包也放入里面.这样在没有安装jre的情况下也能够执行. watermark/2/text/aHR0cDovL2Jsb2cuY ...
- 基于ContentObserver来动态取消或加入屏幕超时任务
前面也说了.ContentObserver能够来监控数据库里某一项数据的变化,当然也能够同一时候监控多个数据项的变化. 笔者在项目中须要改动到屏幕超时的需求,比方在车载业务中,倒车事件发生的时候,是不 ...
- JS学习笔记 - 面向对象
类.对象类:模子对象:产品(成品) 蛋糕(对象) 模子(类) Array 类 arr 对象 Array.push(); 错 arr.push(); 对 new arr(); 错 原型prototype ...
- POJ 2236 Wireless Network ||POJ 1703 Find them, Catch them 并查集
POJ 2236 Wireless Network http://poj.org/problem?id=2236 题目大意: 给你N台损坏的电脑坐标,这些电脑只能与不超过距离d的电脑通信,但如果x和y ...
- 深入理解线程本地变量ThreadLocal
ThreadLocal理解: 假设在多线程并发环境中.一个可变对象涉及到共享与竞争,那么该可变对象就一定会涉及到线程间同步操作,这是多线程并发问题. 否则该可变对象将作为线程私有对象,可通过Threa ...
- SpringMVC实战(三种控制器方式)
1.前言 上篇博客着重说了一下SpringMVC中几种处理映射的方式,这篇博客来说一下SpringMVC中几种经常使用的控制器. 2.经常使用控制器 2.1 ParameterizableViewC ...
- [CSS] Target empty elements using the :empty pseudo-class
You can target an element that has no child elements by using the :empty pseudo-class. With browser ...
- iOS数据存储简要笔记
1. 数据存储常用的方式 (1)XML 属性列表(plist)归档 (2)preference(偏好设置) (3)NSKeyedArchiver归档(NSCoding) (4) SQLite3 ...
- 如何使用google地图的api(整理)
如何使用google地图的api(整理) 一.总结 一句话总结:直接用script标签引google地图api即可. 1.如何使用google地图的api? 页面引用javascript文件<s ...
- vs 外部依赖项、附加依赖项以及如何添加依赖项目
我们在 VS 中创建 Win32 控制台应用程序,vs 会为解决方案创建默认地创建 4 个 filters(资源管理器中没有对应的目录和文件夹): 头文件:一般为 .h 文件 外部依赖项 源文件:一般 ...