ASP.NET中SqlDataReader生成动态Lambda表达式的实例详解


本文摘自PHP中文网,作者Y2J,侵删。

这篇文章主要介绍了SqlDataReader生成动态Lambda表达式,需要的朋友可以参考下

上一扁使用动态lambda表达式来将DataTable转换成实体,比直接用反射快了不少。主要是首行转换的时候动态生成了委托。

后面的转换都是直接调用委托,省去了多次用反射带来的性能损失。

今天在对SqlServer返回的流对象 SqlDataReader 进行处理,也采用动态生成Lambda表达式的方式转换实体。

先上一版代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

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 无法转换成实体");

   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();

  }

 }

}

在上一篇的基础上增加了 SqlDataReader 的扩展方法

以下代码是调用

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

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返回的对象,处理其它数据库本来是想增加 DbDataReader 的扩展方法,但发现动态生成lambda表达式的地方出错,所以先将现在的

方案记录下来。

以上就是ASP.NET中SqlDataReader生成动态Lambda表达式的实例详解的详细内容!

相关阅读 >>

深入了解asp.net mvc与webform的区别

实例介绍asp.net项目开发中枚举的使用

asp.net mvc 4 中的json数据交互的方法

asp.net中时间格式化的几种方法

解决win7安装visual studio 2015失败的方法

[asp.net mvc 小牛之路]07 - url routing

asp.net中怎样用mvc5的miniprofiler对mvc进行性能监控

asp.net怎么使用js文件

asp.net mvc如何使用bootstrap的实例分析

asp.net与asp有什么不同

更多相关阅读请进入《sqldatareader》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...