直接上代码:

根据属性进行映射:DataTable转化成实体List

public static class DataTableExtension
{
public static List<T> ToList<T>(this DataTable dt)
{
if (dt == null || dt.Rows.Count == )
{
return null;
} List<T> entites = new List<T>(); foreach (DataRow dr in dt.Rows)
{
T t = (T)Activator.CreateInstance(typeof(T));
for (int i = ; i < dr.Table.Columns.Count; i++)
{
PropertyInfo propertyInfo = t.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
if (propertyInfo != null && dr[i] != DBNull.Value)
propertyInfo.SetValue(t, dr[i], null);
} entites.Add(t);
}
return entites;
}
}
}

但是需求往往没有这么简单,如果属性名称和列名不一致,如列名是excel导入过来的,就很有可能是汉字。

我的解决办法就是,在实体模型中,添加Attribute,来注明每个属性和列名的对应关系,如下:

public class Bill
{
[Column("序号")]
public int Id { get; set; } [Column("姓名")]
public string PatientName { get; set; } [Column("结算日期")]
public DateTime BillDate { get; set; } }

现在有两种映射方式了,为了使代码不要太难看,只能重构一下:

public static class DataTableExtension
{
public static List<T> ToList<T>(this DataTable dt, IRowMapper<T> rowMapper)
{
if (dt == null || dt.Rows.Count == )
{
return null;
} List<T> entites = new List<T>(); foreach (DataRow dr in dt.Rows)
{
var t = rowMapper.MapRow(dr); entites.Add(t);
}
return entites;
}
}

添加了一个接口IRowMapper,表明是属性映射,还是自定义的映射。

来看下自定义映射具体的实现:

public class ColumnAttributeMapper<T> : IRowMapper<T>
{
private static Dictionary<string, Dictionary<string, string>> ColumnPropertyMapper= new Dictionary<string, Dictionary<string, string>>(); public ColumnAttributeMapper()
{
if (!ColumnPropertyMapper.ContainsKey(typeof(T).Name))
{
Dictionary<string, string> dict = new Dictionary<string, string>(); var props = typeof(T).GetProperties(); foreach (var prop in props)
{
var attribute = prop.GetCustomAttributes(true).OfType<ColumnAttribute>().FirstOrDefault();
dict.Add(attribute.Name, prop.Name); }
ColumnPropertyMapper.Add(typeof(T).Name, dict);
} } public T MapRow(DataRow dr)
{
T t = (T)Activator.CreateInstance(typeof(T));
for (int i = ; i < dr.Table.Columns.Count; i++)
{
if (ColumnPropertyMapper.ContainsKey(t.GetType().Name))
{
var dict = ColumnPropertyMapper[t.GetType().Name];
var property = dict[dr.Table.Columns[i].ColumnName]; PropertyInfo propertyInfo = t.GetType().GetProperty(property);
if (propertyInfo != null && dr[i] != DBNull.Value)
propertyInfo.SetValue(t, dr[i], null);
}
} return t;
}
}

在构造函数中定义了一个静态的字典,用于存储实体中列名和属性名的对应关系(这里有点绕,我还没想到更好的方法!),

具体调用方法:

  public static void TestPropertyMapper()
{
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("PatientName", typeof(string));
dt.Columns.Add("BillDate", typeof(DateTime)); dt.Rows.Add(, "HKK", DateTime.Now);
dt.Rows.Add(, "WQ", DateTime.Now);
dt.Rows.Add(, "HS", DateTime.Now); List<Bill> bills = dt.ToList<Bill>(rowMapper: new PropertyColumnMapper<Bill>());
}
private static void TestColumnMapper()
{
DataTable dt = new DataTable();
dt.Columns.Add("序号", typeof(int));
dt.Columns.Add("姓名", typeof(string));
dt.Columns.Add("结算日期", typeof(DateTime)); dt.Rows.Add(, "HKK", DateTime.Now);
dt.Rows.Add(, "WQ", DateTime.Now);
dt.Rows.Add(, "HS", DateTime.Now); List<Bill> bills = dt.ToList<Bill>(rowMapper: new ColumnAttributeMapper<Bill>());
}

代码上传到github:https://github.com/hankuikuide/ExcelAccessor/tree/master/Han.DataAccess

DataTable扩展:转化实体ToList的更多相关文章

  1. DataTable数据转换为实体

    我们在用三层架构编写软件时,常常会遇到例如以下问题,就是三层之间的參数传递问题:假设我们在D层查询出数据是DataTable类型的,那么我们在B层甚至U层使用这条数据时,就要用DataTable类型来 ...

  2. DataTable转换为Model实体对象

    记得在学校的时候,接触得最多的就是SqlHelper,每次在读取的时候不管是DataTable还是DataReader转换为实体对象的时候是最恼火的,因为要写很多代码,而且没有什么意义.后面接触到了反 ...

  3. C# DataTable转换成实体列表 与 实体列表转换成DataTable

    /// <summary> /// DataTable转换成实体列表 /// </summary> /// <typeparam name="T"&g ...

  4. DataTable扩展方法ToList<T>()、ToJSON()、ToArrayList()

    /// <summary> /// 扩展方法类 /// </summary> public static class CommonExtension { /// <sum ...

  5. DataTable填补了实体类返回泛型集合

    坤哥见我昨天找了一段代码,如下面: 略微解释下,这段代码时D层查询结束后,将datatable查询到的结果赋值给实体对象的属性,然后返回实体的过程.坤哥看了之后问我,假设实体有500多个属性,难道也要 ...

  6. C#把 DataTable转换为Model实体

    public static List<T> GetModelFromDB<T>( DataTable dt ) { List<T> data = new List& ...

  7. (转)DATATABLE(DATASET)与实体类之间的互转.

    转自:http://www.cnblogs.com/zzyyll2/archive/2010/07/20/1781649.html dataset和实体类 之间的转换 //dataset转实体类  代 ...

  8. DataTable转换成实体

    public static class DataTableToEntity { /// <summary> /// 将DataTable数据源转换成实体类 /// </summary ...

  9. C# DataTable扩展方法

    在日常搬砖中,总结了一些简单的扩展方法. public static bool IsNullOrEmpty(this DataTable dt) { ; } public static bool Is ...

随机推荐

  1. 前端开发 - JQuery - 中

    十四.jquery属性操作 attr prop <!DOCTYPE html> <html lang="en"> <head> <meta ...

  2. Using virtual lists

    Download demo project - 15.7 Kb Contents Introduction Virtual list Creating a virtual list Add items ...

  3. Git添加本地项目出现fatal: unable to get credential storage lock: File exists

    把本地项目初始化之后上传到github上出现问题:fatal: unable to get credential storage lock: File exists 解决办法:是因为我上传用的git帐 ...

  4. 在MFC里面使用ADO访问微软的ACCESS数据库 实现增删改查

    声明:百度以外的公司可以自由转载该文. 正如我上一篇博文提到,ADO这货和MFC没有任何关系,ADO 是一个独立的组件.所以为了使用ADO 我们就要把ADO引入到MFC中. ADO是硬盘上的表现形式是 ...

  5. python16_day24【restful、crm表构、认证】

    一.restful 1. pip install djangorestframework 2.settings.py INSTALLED_APPS = ( ... 'rest_framework', ...

  6. 一步一步学EF系列三【数据迁移】

    我们每篇的内容都不多,所以希望在学习的过程中最后能亲自敲一下代码 这样更有利于掌握. 我们现在接着上篇的例子,我们现在给随便的表增加一个字段 CreateTime 创建日期 运行一下 看看会怎么样 修 ...

  7. zabbix 4.0 安装配置

    1.安装软件包: 1.安装软件包: yum install -y httpd mariadb-server mariadb php php-mysql php-gd libjpeg* php-ldap ...

  8. ubuntu 16.4安装卸载apache+php+mysql

    1.安装apache sudo apt-get update sudo apt-get install apache2 2.安装php5.6 添加PPA源:add-apt-repository ppa ...

  9. quartz (一) 基于 Quartz 开发企业级任务调度应用

    本文转自:http://www.ibm.com/developerworks/cn/opensource/os-cn-quartz/ Quartz 基本概念及原理 Quartz Scheduler 开 ...

  10. H5 动画:轨迹移动 | H5游戏 推金币

    https://aotu.io/notes/2017/11/06/path-animation/ https://aotu.io/notes/2017/11/06/coindozer/