/// <summary>
/// The data extension.
/// </summary>
public static class DataExtension
{
/// <summary>
/// ToList
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="reader">reader</param>
/// <returns>T</returns>
public static List<T> ToList<T>(this IDataReader reader) where T : class, new()
{
var result = new List<T>(); DataTable dt = reader.GetSchemaTable();
try
{
while (reader.Read())
{
var t = new T(); if (dt != null)
{
foreach (DataRow dr in dt.Rows)
{
// 当前列名&属性名
string columnName = dr[].ToString();
PropertyInfo pro = typeof(T).GetProperty(columnName); if (pro == null)
{
continue;
} if (!pro.CanWrite)
{
continue;
} pro.SetValue(t, ConvertExtension.ConvertHelper(reader[columnName], pro.PropertyType), null);
}
} result.Add(t);
}
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
if (!reader.IsClosed)
{
reader.Dispose();
reader.Close();
}
} return result;
} /// <summary>
/// ToList
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="dt">dt</param>
/// <returns>T</returns>
public static List<T> ToList<T>(this DataTable dt) where T : class, new()
{
var result = new List<T>();
foreach (DataRow dr in dt.Rows)
{
var t = new T();
try
{
foreach (DataColumn column in dt.Columns)
{
// 当前列名&属性名
string columnName = column.ColumnName;
PropertyInfo pro = typeof(T).GetProperty(columnName); if (pro == null)
{
continue;
} if (!pro.CanWrite)
{
continue;
} pro.SetValue(t, ConvertExtension.ConvertHelper(dr[columnName], pro.PropertyType), null);
}
}
catch (System.Exception ex)
{
throw ex;
} result.Add(t);
} return result;
} /// <summary>
/// ToList
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="ds">ds</param>
/// <returns>T</returns>
public static List<T> ToList<T>(this DataSet ds) where T : class, new()
{
return ds.Tables[].ToList<T>();
} /// <summary>
/// ToList
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="ds">ds</param>
/// <param name="dataTableIndex">dataTableIndex</param>
/// <returns>T</returns>
public static List<T> ToList<T>(this DataSet ds, int dataTableIndex) where T : class, new()
{
return ds.Tables[dataTableIndex].ToList<T>();
} /// <summary>
/// ToModel
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="reader">reader</param>
/// <returns>T</returns>
public static T ToModel<T>(this IDataReader reader) where T : class, new()
{
var t = new T();
DataTable dt = reader.GetSchemaTable();
try
{
while (reader.Read())
{
if (dt != null)
{
foreach (DataRow dr in dt.Rows)
{
// 当前列名&属性名
string columnName = dr[].ToString();
PropertyInfo pro = typeof(T).GetProperty(columnName); if (pro == null)
{
continue;
} if (!pro.CanWrite)
{
continue;
} pro.SetValue(t, ConvertExtension.ConvertHelper(reader[columnName], pro.PropertyType), null);
}
}
}
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
if (!reader.IsClosed)
{
reader.Dispose();
reader.Close();
}
} return t;
} /// <summary>
/// ToModel
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="dt">dt</param>
/// <returns>T</returns>
public static T ToModel<T>(this DataTable dt) where T : class, new()
{
var t = new T();
if (dt.Rows.Count <= )
{
return t;
} try
{
foreach (DataColumn column in dt.Columns)
{
// 当前列名&属性名
string columnName = column.ColumnName;
PropertyInfo pro = typeof(T).GetProperty(columnName);
if (pro == null)
{
continue;
} if (!pro.CanWrite)
{
continue;
} pro.SetValue(t, ConvertExtension.ConvertHelper(dt.Rows[][columnName], pro.PropertyType), null);
}
}
catch (System.Exception ex)
{
throw ex;
} return t;
} /// <summary>
/// ToModel
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="ds">ds</param>
/// <param name="dataTableIndex">dataTableIndex</param>
/// <returns>T</returns>
public static T ToModel<T>(this DataSet ds, int dataTableIndex = ) where T : class, new()
{
return ds.Tables[].ToModel<T>();
}
}

DataExtension

     /// <summary>
/// The convert extension.
/// </summary>
public static class ConvertExtension
{
/// <summary>
/// The convert helper.
/// </summary>
/// <param name="value">
/// The value.
/// </param>
/// <param name="conversionType">
/// The conversion type.
/// </param>
/// <returns>
/// The <see cref="object"/>.
/// </returns>
public static object ConvertHelper(object value, Type conversionType)
{
Type nullableType = Nullable.GetUnderlyingType(conversionType); // 判断当前类型是否可为 null
if (nullableType != null)
{
if (value == DBNull.Value)
{
return null;
} // 若是枚举 则先转换为枚举
if (nullableType.IsEnum)
{
value = System.Enum.Parse(nullableType, value.ToString());
} return Convert.ChangeType(value, nullableType);
} if (conversionType.IsEnum)
{
return System.Enum.Parse(conversionType, value.ToString());
} return Convert.ChangeType(value, conversionType);
} /// <summary>
/// The convert to decimal null.
/// </summary>
/// <param name="targetObj">
/// The target obj.
/// </param>
/// <returns>
/// The <see cref="decimal"/>.
/// </returns>
public static decimal? ConvertToDecimalNull(object targetObj)
{
if (targetObj == null || targetObj == DBNull.Value)
{
return null;
} return Convert.ToDecimal(targetObj);
} /// <summary>
/// The convert to int null.
/// </summary>
/// <param name="targetObj">
/// The target obj.
/// </param>
/// <returns>
/// The <see cref="int"/>.
/// </returns>
public static int? ConvertToIntNull(object targetObj)
{
if (targetObj == null || targetObj == DBNull.Value)
{
return null;
} return Convert.ToInt32(targetObj);
} /// <summary>
/// The convert to string.
/// </summary>
/// <param name="obj">
/// The obj.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string ConvertToString(object obj)
{
return obj == null ? string.Empty : obj.ToString();
} /// <summary>
/// 将泛类型集合List类转换成DataTable
/// </summary>
/// <param name="entitys">泛类型集合</param>
/// <typeparam name="T">T</typeparam>
/// <returns>DataTable</returns>
public static DataTable ListToDataTable<T>(List<T> entitys)
{
// 检查实体集合不能为空
if (entitys == null || entitys.Count < )
{
throw new System.Exception("需转换的集合为空");
} // 取出第一个实体的所有Propertie
Type entityType = entitys[].GetType();
PropertyInfo[] entityProperties = entityType.GetProperties(); // 生成DataTable的structure
// 生产代码中,应将生成的DataTable结构Cache起来,此处略
DataTable dt = new DataTable();
foreach (PropertyInfo t in entityProperties)
{
// dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
dt.Columns.Add(t.Name);
} // 将所有entity添加到DataTable中
foreach (object entity in entitys)
{
// 检查所有的的实体都为同一类型
if (entity.GetType() != entityType)
{
throw new System.Exception("要转换的集合元素类型不一致");
} object[] entityValues = new object[entityProperties.Length];
for (int i = ; i < entityProperties.Length; i++)
{
entityValues[i] = entityProperties[i].GetValue(entity, null);
} dt.Rows.Add(entityValues);
} return dt;
} /// <summary>
/// 转换中文星期
/// </summary>
/// <param name="dt">The dt.</param>
/// <returns>Week.</returns>
public static Week ConverToWeekByZHCN(this DateTime dt)
{
return (Week)dt.DayOfWeek;
} /// <summary>
/// 四舍五入保留2位小数(中国式)
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
public static decimal DecimalTwoPlaces(this decimal d)
{
return Math.Round(d, , MidpointRounding.AwayFromZero);
}
}

ConvertExtension

将 IDataReader DataSet DataTable 转化成 List<T> Or T类型
上面是转化代码

DataTable转化成实体对象的更多相关文章

  1. DataTable转换为Model实体对象

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

  2. 简单的反射 把datatable 转换成list对象

    /// <summary> /// 把datatable 转换成list对象 /// </summary> /// <typeparam name="T&quo ...

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

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

  4. DataTable转换成实体

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

  5. XML中的非法字符转化成实体

    问题 如果XML有非法字符比如 "·",或者HTML标签<br/>.XML在解析的过程中就会出错.就无法正常解析,或者把xml反射成实体. 有些字符,像(<)这类 ...

  6. DataTable转成实体列表 和 DataRow转成实体类

    #region DataTale转为实体列表 /// <summary> /// DataTale转为实体列表 /// </summary> /// <typeparam ...

  7. json数据转化成实体 存到数据库.

    直接看步骤吧 1.一般我们会调用别人给的webservice获取一个字符串数据.如果为String data="xxxxxxxxxx";  这个data事实上就是样例Enterpr ...

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

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

  9. DataTable 转换成 Json的3种方法

    在web开发中,我们可能会有这样的需求,为了便于前台的JS的处理,我们需要将查询出的数据源格式比如:List<T>.DataTable转换为Json格式.特别在使用Extjs框架的时候,A ...

随机推荐

  1. [LeetCode] 458. Poor Pigs_Easy tag: Math

    There are 1000 buckets, one and only one of them contains poison, the rest are filled with water. Th ...

  2. [转]C语言四书五经

    我们来说说C语言方面的图书.什么,C语言?有读者奇怪了.没错,这一次的主角就是诞生于1973年如今已经儿孙满堂的C语言.我们之所以要谈及C,不仅仅是因为它的影响深远,这完全可以从C系列语言家族的兴旺发 ...

  3. volatile的语义与实现

    1.volatile关键字的两层语义 一旦一个共享变量(类的成员变量.类的静态成员变量)被volatile修饰之后,那么就具备了两层语义: 1)保证了不同线程对这个变量进行操作时的可见性,即一个线程修 ...

  4. 查看mysql主外键信息

    SELECT  *FROMinformation_schema.key_column_usage tWHERE t.constraint_schema = '库名称'AND t.constraint_ ...

  5. discuz注册页修改

    大家好!近来备受发帖机困扰,备受垃圾帖子困扰.一直以来都纯粹在删帖当中,本来网站服务器就是国内服务器,这样一来很多关键字是禁止的,可不管如何设置防灌水还是无法杜绝这一事项,特别是国内空间的网站,一出现 ...

  6. 防DNS劫持教程,手动修复本地DNS教程

    防DNS劫持教程,手动修复本地DNS教程 该如何避免DNS劫持的问题呢?1. 请不要轻易连接陌生网络.2. 可以通过手动指定DNS(DNS用于将域名正确转换为您想访问的网站的作用),修改后你的网络应用 ...

  7. MySQL Crash Course #12# Chapter 18. Full-Text Searching

    INDEX 由于性能.智能结果等多方面原因,在搜索文本时,全文搜索一般要优于通配符和正则表达式,前者为指定列建立索引,以便快速找到对应行,并且将结果集智能排序.启用查询扩展可以让我们得到未必包含关键字 ...

  8. Python3.x:抓取百事糗科段子

    Python3.x:抓取百事糗科段子 实现代码: #Python3.6 获取糗事百科的段子 import urllib.request #导入各类要用到的包 import urllib import ...

  9. Android实践项目汇报(四)

    全国天气客户端 本周学习计划 添加修改功能,完成项目 实际完成情况 1.成功显示当天及后几天的天气信息 通过修改chaxun.java程序,比较JSON数据格式中JSONObject("to ...

  10. Android实践项目汇报(三)

    Google天气客户端 本周学习计划 调试代码使之成功运行并实现天气预报功能. 实际完成情况 由于google取消api接口服务,天气源的传输.所以我换了一个使用 haoserver API接口的程序 ...