上一扁使用动态lambda表达式来将DataTable转换成实体,比直接用反射快了不少。主要是首行转换的时候动态生成了委托。
后面的转换都是直接调用委托,省去了多次用反射带来的性能损失。
今天在对SqlServer返回的流对象 SqlDataReader 进行处理,也采用动态生成Lambda表达式的方式转换实体。
先上一版代码
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 的扩展方法
以下代码是调用
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表达式的地方出错,所以先将现在的
方案记录下来。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。