在开发中,把查询结果以datatable返回很方便,但是在检索数据时又很麻烦,没有模型类型检索方便。
所以很多人都是按照以下方式做的:
// 获得查询结果
datatable dt =
dbhelper.executedatatable(...);
//
把datatable转换为ilist<userinfo>
ilist<userinfo> users =
converttouserinfo(dt);
问题:如果此系统有几十上百个模型,那不是每个模型中都要写个把datatable转换为此模型的方法吗?
解决:能不能写个通用类,可以把datatable转换为任何模型,呵呵,这就需要利用反射和泛型了
不多说,核心代码如下,经过测试,性能不错,大家可以根据实际情况改善
using system;
using system.collections.generic;
using system.text;
using system.data;
using system.reflection;
namespace ncl.data
{
/// <summary>
/// 实体转换辅助类
/// </summary>
public class modelconverthelper<t> where t : new()
{
public static ilist<t> converttomodel(datatable dt)
{
// 定义集合
ilist<t> ts = new list<t>();
// 获得此模型的类型
type type = typeof(t);
string tempname = "";
foreach (datarow dr in dt.rows)
{
t t = new t();
// 获得此模型的公共属性
propertyinfo[] propertys = t.gettype().getproperties();
foreach (propertyinfo pi in propertys)
{
tempname = pi.name;
// 检查datatable是否包含此列
if (dt.columns.contains(tempname))
{
// 判断此属性是否有setter
if (!pi.canwrite) continue;
object value = dr[tempname];
if (value != dbnull.value)
pi.setvalue(t, value, null);
}
}
ts.add(t);
}
return ts;
}
}
}
使用方式:
modelconverthelper<userinfo>.converttomodel(dt);
呵呵,这样子是不是很方便了,谢谢,希望能给你带来收获!