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的更多相关文章

  1. SqlDataReader生成动态Lambda表达式

    上一扁使用动态lambda表达式来将DataTable转换成实体,比直接用反射快了不少.主要是首行转换的时候动态生成了委托. 后面的转换都是直接调用委托,省去了多次用反射带来的性能损失. 今天在对Sq ...

  2. 动态生成C# Lambda表达式

    转载:http://www.educity.cn/develop/1407905.html,并整理! 对于C# Lambda的理解我们在之前的文章中已经讲述过了,那么作为Delegate的进化使用,为 ...

  3. C# 构建动态Lambda表达式

    做CURD开发的过程中,通常都会需要GetList,然而查询条件是一个可能变化的需求,如何从容对应需求变化呢? 首先,我们来设计一个套路,尝试以最小的工作量完成一次查询条件的需求变更 1.UI收集查询 ...

  4. EntityFramework使用动态Lambda表达式筛选数据

    public static class PredicateBuilder { public static Expression<Func<T, bool>> True<T ...

  5. 动态LINQ(Lambda表达式)构建

    using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; us ...

  6. C# 动态构建表达式树(一)—— 构建 Where 的 Lambda 表达式

    C# 动态构建表达式树(一)-- 构建 Where 的 Lambda 表达式 前言 记得之前同事在做筛选功能的时候提出过一个问题:如果用户传入的条件数量不确定,条件的内容也不确定(大于.小于和等于), ...

  7. Lambda表达式详解

    前言 1.天真热,程序员活着不易,星期天,也要顶着火辣辣的太阳,总结这些东西. 2.夸夸lambda吧:简化了匿名委托的使用,让你让代码更加简洁,优雅.据说它是微软自c#1.0后新增的最重要的功能之一 ...

  8. lambda表达式-转载

    来源:http://www.cnblogs.com/knowledgesea/p/3163725.html   前言 1.天真热,程序员活着不易,星期天,也要顶着火辣辣的太阳,总结这些东西. 2.夸夸 ...

  9. C# lambda表达式(简单易懂)

    前言 1.天真热,程序员活着不易,星期天,也要顶着火辣辣的太阳,总结这些东西. 2.夸夸lambda吧:简化了匿名委托的使用,让你让代码更加简洁,优雅.据说它是微软自c#1.0后新增的最重要的功能之一 ...

随机推荐

  1. amazeui页面分析之登录页面

    amazeui页面分析之登录页面 一.总结 1.tpl命名空间:tpl命名空间的样式都是从app.css里面来的,app.css用用来移动网站开发的样式 2.表单样式:am-form到am-form- ...

  2. equals、HashCode与实体类的设计

    equals和HashCode都是用来去重的,即判断两个对象是否相等.如果是String类则我们直接用.equals()判断,如果是我们自己定义的类,需要有自己的判断方法,重写equals,如果是集合 ...

  3. Access WMI via Python from Linux

    You can use Impacket (https://github.com/CoreSecurity/impacket) that has WMI implemented in Python. ...

  4. [Angular] Setup automated deployment with Angular, Travis and Firebase

    Automate all the things!! Automation is crucial for increasing the quality and productivity. In this ...

  5. jQuery笔记---选择器(二)

    1.选择器练习: 1)查找UL中的元素的内容 格式:$(“ul li:XX”).text() XX:代表方法 比如:获取到第一元素,然后获取当中的值 $(“ul li:first”).text() 获 ...

  6. Java抽象类中的抽象方法的参数对应的子类的方法的参数必须一致吗?

    同学你这个涉及了两个概念. 一个是抽象方法,一个是方法重载. 先说下概念: 抽象方法就是abstract描述的方法,它本身不含实现,必须由子类实现. 方法重载则是同一个方法名,但是参数类型或者参数个数 ...

  7. Hibernate与代理模式

    代理模式:当须要调用某个对象的时候.不须要关心拿到的是不是一定是这个对象,它须要的是,我拿到的这个对象能够完毕我想要让它完毕的任务就可以,也就是说.这时调用方能够拿到一个代理的一个对象,这个对象能够调 ...

  8. cocos 关于文件名称的各种坑 各种斜杠坑

    cocos 全部文件路径 的斜杠 必须 用 /  而不能够用 \ 不然编译到安卓各种坑 相对路径 第一个字符不可 带 / /*比如 res/test.png 这样的应该是标准的 /res/test.p ...

  9. 29、从零写USB摄像头驱动之通过urb接受数据后上报数据是函数中fid的作用

    原因分析如下: 视频数据是由一帧一帧数据组成,为了防止数据错乱,会给每一帧数据分配一个frameid,从第0帧开始,接着是第1帧,接着又是第0帧这样交错进行的,对usb摄像头来说每一帧数据来源于多个包 ...

  10. 【b601】能量项链

    Time Limit: 1 second Memory Limit: 50 MB [问题描述] 在Mars星球上,每个Mars人都随身佩带着一串能量项链.在项链上有N颗能量珠.能量珠是一颗有头标记与尾 ...