对DataSet,DataRow,DateTable转换成相应的模型
/// <summary>
/// DataRow 转成 模型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dr"></param>
/// <returns></returns>
public static T ToModel<T>(this DataRow dr) where T : class, new()
{
T ob = new T();
if (dr != null)
{
Type vType = typeof(T);
//创建一个属性的列表
PropertyInfo[] prlist = vType.GetProperties(); DataColumnCollection vDataCoulumns = dr.Table.Columns;
try
{
foreach (PropertyInfo vProInfo in prlist)
{
if (vDataCoulumns.IndexOf(vProInfo.Name) >= && dr[vProInfo.Name] != DBNull.Value)
{
vProInfo.SetValue(ob, dr[vProInfo.Name], null);
}
}
}
catch (Exception ex)
{ }
}
return ob;
}
/// <summary>
/// DataTable 转换为List 集合
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="dt">DataTable</param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable dt) where T : class, new()
{
//创建一个属性的列表
List<PropertyInfo> prlist = new List<PropertyInfo>();
//获取TResult的类型实例 反射的入口
Type t = typeof(T);
//获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表
Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -) prlist.Add(p); });
//创建返回的集合
List<T> oblist = new List<T>();
if (dt != null)
{
foreach (DataRow row in dt.Rows)
{
try
{
//创建TResult的实例
T ob = new T();
//找到对应的数据 并赋值
prlist.ForEach(p =>
{
if (dt.Columns.IndexOf(p.Name) >= && row[p.Name] != DBNull.Value)
{
try
{
//如果是泛型
if (p.PropertyType.ToString().IndexOf("System.Nullable") > -)
{
string types = p.PropertyType.ToString().Substring(p.PropertyType.ToString().IndexOf("[") + );
types = types.Substring(, types.Length - ); Type typeinfo = Type.GetType(types);
p.SetValue(ob, Convert.ChangeType(row[p.Name], typeinfo), null); }
else
{
p.SetValue(ob, Convert.ChangeType(row[p.Name], p.PropertyType), null);//类型转换
}
}
catch (Exception ex)
{
LogUtility.WriteLogForExcepiton(ex);
} }
});
//放入到返回的集合中.
oblist.Add(ob);
}
catch (Exception ex)
{
}
}
}
return oblist;
}
/// <summary>
/// DataSet转换为泛型集合
/// </summary>
/// <typeparam name="T">泛型类型</typeparam>
/// <param name="ds">DataSet数据集</param>
/// <param name="tableIndex">待转换数据表索引,默认第0张表</param>
/// <returns>返回泛型集合</returns>
public static IList<T> ToList<T>(this DataSet ds, int tableIndex = )
{ if (ds == null || ds.Tables.Count < ) return null;
if (tableIndex > ds.Tables.Count - )
return null; if (tableIndex < )
tableIndex = ; DataTable dt = ds.Tables[tableIndex]; // 返回值初始化
IList<T> result = new List<T>();
for (int j = ; j < dt.Rows.Count; j++)
{
T _t = (T)Activator.CreateInstance(typeof(T));
PropertyInfo[] propertys = _t.GetType().GetProperties(); foreach (PropertyInfo pi in propertys)
{
for (int i = ; i < dt.Columns.Count; i++)
{ // 属性与字段名称一致的进行赋值
if (pi.Name.Equals(dt.Columns[i].ColumnName))
{ // 数据库NULL值单独处理
if (dt.Rows[j][i] != DBNull.Value)
pi.SetValue(_t, dt.Rows[j][i], null);
else
pi.SetValue(_t, null, null);
break;
}
}
}
result.Add(_t);
}
return result;
} /// <summary>
/// DataSet转换为泛型集合
/// </summary>
/// <typeparam name="T">泛型类型</typeparam>
/// <param name="ds">DataSet数据集</param>
/// <param name="tableName">待转换数据表名称,名称为空时默认第0张表</param>
/// <returns>返回泛型集合</returns>
public static IList<T> ToList<T>(this DataSet ds, string tableName)
{ int _TableIndex = ; if (ds == null || ds.Tables.Count < )
return null; if (string.IsNullOrEmpty(tableName))
return ToList<T>(ds, ); for (int i = ; i < ds.Tables.Count; i++)
{ // 获取Table名称在Tables集合中的索引值
if (ds.Tables[i].TableName.Equals(tableName))
{
_TableIndex = i;
break;
}
}
return ToList<T>(ds, _TableIndex);
}
对DataSet,DataRow,DateTable转换成相应的模型的更多相关文章
- 将DataSet(DataTable)转换成JSON格式(生成JS文件存储)
public static string CreateJsonParameters(DataTable dt) { /**/ /**/ /**/ /* /*********************** ...
- 利用泛型和反射,管理配置文件,把Model转换成数据行,并把数据行转换成Model
利用泛型和反射,管理配置文件,把Model转换成数据行,并把数据行转换成Model 使用场景:网站配置项目,为了便于管理,网站有几个Model类来管理配置文件, 比如ConfigWebsiteMo ...
- iOS swift HandyJSON组合Alamofire发起网络请求并转换成模型
在swift开发中,发起网络请求大部分开发者应该都是使用Alamofire发起的网络请求,至于请求完成后JSON解析这一块有很多解决方案,我们今天这里使用HandyJSON来解析请求返回的数据并转化成 ...
- DataSet转换成List<>
方法一: //DataSet转换成List<ArticleInfo> public List<ArticleInfo> GetArticleList(DataSet ds) { ...
- TXT文件转换成DataSet数据集
/// <summary> /// TXT文件转换成DataSet数据集 /// </summary> /// <param name="FilePath&qu ...
- c#将List<T>转换成DataSet
/// <summary> /// List<T> 转换成DataSet /// </summary> /// &l ...
- .net 数据源DataSet 转换成模型
/// <summary> /// DataSet转换成model 自动赋值返回集合 /// </summary> /// <typeparam name="T ...
- DataSet 反射转换成 List<T>
/// <summary> /// DataSet转换成指定返回类型的实体集合 /// </summary> /// <typeparam name="T&qu ...
- 使用linq对ado.net查询出来dataset集合转换成对象(查询出来的数据结构为一对多)
public async Task<IEnumerable<QuestionAllInfo>> GetAllQuestionByTypeIdAsync(int id) { st ...
随机推荐
- c++实现对输入数组进行快速排序
#include "stdafx.h" #include <iostream> #include <string> #include <vector& ...
- 记录code修改
package com.hesheng.myapplication; import android.content.Context;import android.graphics.Bitmap;imp ...
- react-native-mapbox-gl
mapbox是基于谷歌地图集成的地图插件,可以在很多平台使用,具体可以看mapbox官网.这里具体讲解“react-native-mapbox-gl”插件,是mapbox结合react native封 ...
- 如何避免在EF自动生成的model中的DataAnnotation被覆盖掉
摘自ASP.NET MVC 5 网站开发之美 6.4 Metadata与数据验证 如果使用Database-First方式生成*.edms,那么所生成的类文件会在*.tt文件的层级之下,扩展名tt是一 ...
- 遍历查询结果集,update数据
select NULL mykey, * into #mytemp from dbo.DIM_DISTRIBUTOR declare @i int begin ) print @i )) where ...
- request.getRequestDispatcher().forward(request.response)
request.getRequestDispatcher().forward(request.response)中的那两个参数是哪里来的? 2010-11-09 23:13 QQ357169111 | ...
- SecurityError: The operation is insecure.(js不安全操作)
今天突然就遇上了这样的情况,本来在出错的这一行的后面,还有要执行的语句,都没有办法执行,真实坑爹,而最要命的事情,这样的情况,在我的chrome浏览器里没有,但是在firefox里就会出现. The ...
- AngularJs学习笔记--I18n/L10n
原版地址:http://code.angularjs.org/1.0.2/docs/guide/i18n 一.I18n and L10n in AngularJS 1. 什么是I18n和L10n? 国 ...
- 规约模式的ef拼接
public class LamadaExtention<Dto> where Dto : new() { private List<Expression> m_lstExpr ...
- commons.pool2 对象池的使用
commons.pool2 对象池的使用 ? 1 2 3 4 5 <dependency> <groupId>org.apache.commons</groupI ...