分享一个DataTable转List强类型的类库
类库扩展自Datatable,可以直接用Datatable.ToList<T>()进行转换。为了方便把DataReader装入Datatable,开扩展了一个LoadForReader(this DataTable dt, IDataReader reder),用法很简单。看例子。
public override void Execute()
{
using (var conn = DbConnection)
{
conn.Open();
MySqlCommand Command = new MySqlCommand(QuerySql, conn);
var data = new DataTable().LoadForReader(Command.ExecuteReader());
foreach (var item in data.ToList<Admin>(new List<ConvertMapping> { ConvertMapping.Convert("userId", "Id") }))
{
AddEntityToContext(item);
}
}
SavaChangs();
}
DataTable.ToList<T>()有两个可选参数,第一个是“映射关系集合”,另外一个是“自定义转换器”。下面分别说下有什么作用。
1:映射关系集合
假设现在数据库一张Student表,Student表拥有Id,StudentName,StudetnAge,同样,我们在项目中有一个Student类,Student类有Id,Name,Age字段。在进行转换的时候,会自动找同名的属性进行映射复制,Id可以进行赋值,但是StudentName和Age却不行。所以我们要把StudentName和Name建立映射关系。
var mappings = new List<ConvertMapping>{
ConvertMapping.Convert("StudentName","Name"),
ConvertMapping.Convert("StudentAge","Age")
};
2:自定义转换器
假设我们在转换的时候,需要把数据库里面StudentAge字段小于18的在转换的时候全部改成18,就需要用到”自定义转换器”,用法如下:
new DataTable().ToList<Admin>(null, (c, r) =>
{
if (r["StudentAge"] != DBNull.Value && Convert.ToInt32(r["StudentAge"]) < )
{
c.Age = ;
}
else
{
c.Age = Convert.ToInt32(r["StudentAge"]);
}
});
下面贴上代码:
public static class DatatableExtend
{
/// <summary>
/// 表格转换成List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <param name="mappings"></param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable table, IList<ConvertMapping> mappings = null, Action<T, DataRow> convetAc = null) where T : class, new()
{
List<T> result = new List<T>();
if (table == null || table.Rows.Count == )
{
return result;
}
ConvertMapping mappingResult = null;
foreach (DataRow row in table.Rows)
{
T tResult = new T();
foreach (DataColumn column in table.Columns)
{
if (mappings != null)
{
mappingResult = mappings.Where(c => c.SourceColumnName.Equals(column.ColumnName, StringComparison.CurrentCultureIgnoreCase)).SingleOrDefault();
}
if (mappingResult == null)
{
mappingResult = ConvertMapping.Convert(column.ColumnName, column.ColumnName);
}
SetPropertyValue(tResult, mappingResult.NewSourceColumnName, row[mappingResult.SourceColumnName].ToString());
}
convetAc?.Invoke(tResult, row);
result.Add(tResult);
}
return result;
} public static DataTable LoadForReader(this DataTable dt, IDataReader reder)
{
using (reder)
{
dt.Load(reder);
}
return dt;
} private static void SetPropertyValue<T>(T otype, string propertyName, object value)
{
if (otype == null)
{
throw new ArgumentNullException(nameof(otype));
}
var proInfo = otype.GetType().GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
if (proInfo != null)
{
if (proInfo.PropertyType == typeof(bool)&&Microsoft.VisualBasic.Information.IsNumeric(value))
{
value = Convert.ToInt32(value);
}
proInfo.SetValue(otype, Convert.ChangeType(value, proInfo.PropertyType));
}
}
} public class ConvertMapping
{
/// <summary>
/// 源字段
/// </summary>
public string SourceColumnName { get; private set; } /// <summary>
/// 新字段
/// </summary>
public string NewSourceColumnName { get; private set; } private ConvertMapping() { }
public static ConvertMapping Convert<TType, TNewType>(Expression<Func<TType, string>> sourece, Expression<Func<TNewType, string>> newSource)
{
ConvertMapping mapping = new ConvertMapping();
mapping.SourceColumnName = sourece.Parameters.SingleOrDefault()?.Name;
mapping.NewSourceColumnName = newSource.Parameters.SingleOrDefault()?.Name;
return mapping;
} public static ConvertMapping Convert(string sourece, string newSource)
{
ConvertMapping mapping = new ConvertMapping();
mapping.SourceColumnName = sourece;
mapping.NewSourceColumnName = newSource;
return mapping;
}
}
分享一个DataTable转List强类型的类库的更多相关文章
- 分享一个导出数据到 Excel 的类库
起源: 之前在做一个项目时,客户提出了许多的导出数据的需求: 导出用户信息 导出业务实体信息 各种查询都要能导出 导出的数据要和界面上看到的一致 可以分页导出 ... 为了应对用户的这些需求,我决定先 ...
- 分享一个oraclehelper
分享一个拿即用的oraclehelper 首先要引用本机中的oralce access,如果是64位的话,也必须是64位运行,不然会报连接为空connection 等于null. using Orac ...
- 分享一个c#写的开源分布式消息队列equeue
分享一个c#写的开源分布式消息队列equeue 前言 equeue消息队列中的专业术语 Topic Queue Producer Consumer Consumer Group Broker 集群消费 ...
- 分享一个自己写的MVC+EF “增删改查” 无刷新分页程序
分享一个自己写的MVC+EF “增删改查” 无刷新分页程序 一.项目之前得添加几个组件artDialog.MVCPager.kindeditor-4.0.先上几个效果图. 1.首先建立一个数 ...
- 分享一个SqliteHelper类
分享一个SqliteHelper类 SQLite作为一个本地文件数据库相当好用,小巧.快速.支持事务.关系型,甚至可以运行在Android上.在很久以前的一个项目中,我们用过它来将接收到的数据做本地统 ...
- C# PDF Page操作——设置页面切换按钮 C# 添加、读取Word脚注尾注 C#为什么不能像C/C++一样的支持函数只读传参 web 给大家分享一个好玩的东西,也许你那块就用的到
C# PDF Page操作——设置页面切换按钮 概述 在以下示例中,将介绍在PDF文档页面设置页面切换按钮的方法.示例中将页面切换按钮的添加分为了两种情况,一种是设置按钮跳转到首页.下页.上页或者 ...
- 分享一个简单的C#的通用DbHelper类(支持数据连接池)
每次新项目的时候,都要从头去找一遍数据库工具类.这里分享一个简单实用的C#的通用DbHelper工具类,支持数据连接池. 连接池配置 <connectionStrings> <add ...
- 分享一个SQLSERVER脚本(计算数据库中各个表的数据量和每行记录所占用空间)
分享一个SQLSERVER脚本(计算数据库中各个表的数据量和每行记录所占用空间) 很多时候我们都需要计算数据库中各个表的数据量和每行记录所占用空间 这里共享一个脚本 CREATE TABLE #tab ...
- 分享一个MySQL分库分表备份脚本(原)
分享一个MySQL分库备份脚本(原) 开发思路: 1.路径:规定备份到什么位置,把路径(先判断是否存在,不存在创建一个目录)先定义好,我的路径:/mysql/backup,每个备份用压缩提升效率,带上 ...
随机推荐
- Build path entry is missing: config 引起的 The project: configwhich is referenced by the classpath, does not exist.
运行Junit的时候报错, The project: XXXX which is referenced by the classpath, does not exist. 在Java Build Pa ...
- CSS学习摘要-语法和选择器
主要摘自网络开发者. 从最基本的层次来看,CSS是由两块内容组合而成的: 属性(Property):一些人类可理解的标识符,这些标识符指出你想修改哪一些样式,例如:字体,宽度,背景颜色等. 属性值(V ...
- C++ 读书笔记2
dfadsfa body { font-family: Helvetica, arial, sans-serif; font-size: 14px; line-height: 1.6; padding ...
- zabbix的日常监控-API
Zabbix API提供两项主要功能: 远程管理Zabbix配置 远程检索配置和历史数据 官方文档:https://www.zabbix.com/documentation/3.4/zh/manual ...
- October 03rd 2017 Week 40th Tuesday
Don't make promises you can't keep. But those are the best kind. 不要许下做不到的承诺,但是我们做不到的承诺往往是最好的. The be ...
- iis和apache共用80端口,IIS代理转发apache
为什么共用80端口应该不用多说了,服务器上程序运行环境有很多套,都想抢用80端口,所以就有了共用80端口的解决方案. 网上很多的教程一般都是设置APACHE使用默认80端口,代理转发IIS的网站,II ...
- 【原创】uwsgi中多进程+多线程原因以及串行化accept() - thunder_lock说明
如有不对,请详细指正. 最近再研究uwsgi如何部署python app,看uwsgi的文档,里面有太多的参数,但每个参数的解释太苍白,作为菜鸟的我实在是不懂.想搞清楚uwsgi的工作原因以及里面的一 ...
- Joinpoint继承体系-笔记
Joinpoint继承层次图: 由上图可以知道的所有的接口的实现都在ReflectiveMethodInvocation这个类中.ConstructorInvocation接口只有一个方法,这个方法的 ...
- 使用 libffi 实现 AOP
核心还是利用oc消息的查找派发机制,进行类结构的动态修改,用新函数替换老函数,然后再调用老函数. 前言 众所周知,使用runtime的提供的接口,我们可以设定原方法的IMP,或交换原方法和目标 ...
- 1251. 序列终结者【平衡树-splay】
Description 网上有许多题,就是给定一个序列,要你支持几种操作:A.B.C.D.一看另一道题,又是一个序列 要支持几种操作:D.C.B.A.尤其是我们这里的某人,出模拟试题,居然还出了一道这 ...