C# DataTable 转 实体类
C# 中查询结果DataTable转实体类:
比如:List<RtmInterview> rtmList = GetDataById( id);
public List<RtmInterview> GetDataById(string id)
{
List<RtmInterview> rtmList = new List<RtmInterview>();
bool ConnectionOpenHere = false;
try
{
DataTable dt = new DataTable();
if (this.command.Connection.State == System.Data.ConnectionState.Closed) { this.command.Connection.Open(); ConnectionOpenHere = true; }
string strsql = string.Format("select a.*,b.depname from RTM_INTERVIEW a left join rtm_dept b on (a.depid=b.id) where upper(a.id)='{0}'", id);
this.command.CommandText = strsql;
this.dataAdapter.Fill(dt); rtmList = new DatatableToEntity<RtmInterview>().FillModel(dt); dt.Clear();
this.command.CommandText = string.Format("select * from RTM_INTERVIEW_APPROVE where upper(interviewid)='{0}' order by createon desc",id);
this.dataAdapter.Fill(dt);
List<RtmInterviewStep> steplist = new DatatableToEntity<RtmInterviewStep>().FillModel(dt);
rtmList.ForEach(s=>s.ApproveSteps=steplist);
}
catch (Exception ex)
{
throw (ex);
}
finally
{
if (ConnectionOpenHere) { this.command.Connection.Close(); }
}
return rtmList; }
其中:DatatableToEntity 类如下:
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text; namespace HRData.RTM.NewOperate
{
public class DatatableToEntity<T> where T : new()
{
/// <summary>
/// 填充对象列表:用DataSet的第一个表填充实体类
/// </summary>
/// <param name="ds">DataSet</param>
/// <returns></returns>
public List<T> FillModel(DataSet ds)
{
if (ds == null || ds.Tables[] == null || ds.Tables[].Rows.Count == )
{
return null;
}
else
{
return FillModel(ds.Tables[]);
}
} // <summary>
/// 填充对象列表:用DataSet的第index个表填充实体类
/// </summary>
public List<T> FillModel(DataSet ds, int index)
{
if (ds == null || ds.Tables.Count <= index || ds.Tables[index].Rows.Count == )
{
return null;
}
else
{
return FillModel(ds.Tables[index]);
}
} /// <summary>
/// 填充对象列表:用DataTable填充实体类
/// </summary>
public List<T> FillModel(DataTable dt)
{
if (dt == null || dt.Rows.Count == )
{
return null;
}
List<T> modelList = new List<T>();
foreach (DataRow dr in dt.Rows)
{
//T model = (T)Activator.CreateInstance(typeof(T));
T model = new T();
for (int i = ; i < dr.Table.Columns.Count; i++)
{
PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (propertyInfo != null && dr[i] != DBNull.Value)
{
string value = dr[i] == null ? "" : dr[i].ToString();
//string typestr = dr[i].GetType().Name;
//if(typestr.Equals("DateTime"))
//value = dr[i].ToString();
propertyInfo.SetValue(model, value, null);
} } modelList.Add(model);
}
return modelList;
} /// <summary>
/// 填充对象:用DataRow填充实体类
/// </summary>
public T FillModel(DataRow dr)
{
if (dr == null)
{
return default(T);
} //T model = (T)Activator.CreateInstance(typeof(T));
T model = new T(); for (int i = ; i < dr.Table.Columns.Count; i++)
{
PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (propertyInfo != null && dr[i] != DBNull.Value)
{
string value = dr[i] == null ? "" : dr[i].ToString();
//string typestr = dr[i].GetType().Name;
//if(typestr.Equals("DateTime"))
//value = dr[i].ToString();
propertyInfo.SetValue(model, value, null);
}
}
return model;
} }
}
注意: 忽略大小写的方法,比如数据库字段都是大写,但是实体类是C#骆驼峰式或其他写法时不匹配。
所以修改
PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
即可。
C# DataTable 转 实体类的更多相关文章
- DataTable与实体类互相转换
/// <summary> /// DataTable与实体类互相转换 /// </summary> /// <typeparam name="T"& ...
- .net 根据匿名类生成实体类,根据datatable生成实体类,根据sql生成实体类
在开发中可能会遇到这几种情况 1.EF或LINQ查询出来的匿名对象在其它地方调用不方便,又懒的手动建实体类 2.通过datatable反射实体需要先建一个类 ,头痛 3.通过SQL语句返回的实体也需要 ...
- DataTable与实体类的转换
多年前写的DataTable与实体类的转换,已放github 阅读目录 介绍 起因 代码 UnitTest GitHub 介绍 很多年前一直使用Ado.net,后来慢慢转型到其他的orm,在转型过程中 ...
- DataTable转实体类
/// <summary> /// DataTable与实体类互相转换 /// </summary> /// <typeparam name="T"& ...
- 【转】DataTable与实体类互相转换
原文地址:https://www.cnblogs.com/marblemm/p/7084797.html /// <summary> /// DataTable与实体类互相转换 /// & ...
- DataTable和实体类通过反射相互转换
using System.Runtime.Serialization; using System.Data; using System.Reflection; using System.Collect ...
- datatable与实体类之间相互转化的几种方法
#region DataTable转换成实体类 /// <summary> /// 填充对象列表:用DataSet的第一个表填充实体类 /// </summary> /// & ...
- 用DataTable填充实体类List
/// <summary> /// 用DataTable填充实体类List /// </summary> public static List<T> FillLis ...
- 泛型的运用(用于查询数据后DataTable转实体类)
2019.8.14 更新 补全了DataTable转泛型集合的方法: /// <summary> /// DataTable转实体类集合 /// </summary> /// ...
随机推荐
- DeepLearning.ai学习笔记(五)序列模型 -- week1 循环序列模型
一.为什么选择序列模型 序列模型可以用于很多领域,如语音识别,撰写文章等等.总之很多优点... 二.数学符号 为了后面方便说明,先将会用到的数学符号进行介绍. 以下图为例,假如我们需要定位一句话中人名 ...
- Django 实现list页面检索
在list.html写入from表单 在views渲染list方法写入,从前台获取的searchtitle根据name实现检索
- shiro-core包引用的版本问题
在做shiro学习时,遇到这样的问题: Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/ ...
- day02 解释器安装及初识变量
今日内容: 1.解释器的安装 2.添加到环境变量 3.pip初识 4.变量初识 5.PyCharm安装及激活 今日重点: 1.将python及pip添加到环境变量 在将python解释器安装到计算机后 ...
- C# .Net List<T>中Remove()、RemoveAt()、RemoveRange()、RemoveAll()的区别,List<T>删除汇总
在List<T>中删除主要有Remove().RemoveAt().RemoveRange().RemoveAll()这几个方法.下面一一介绍使用方法和注意点. 我们以List<st ...
- BsonJavaScript
BsonJavaScript主要应用于mongodb驱动中 1.进行数据分组 MongoClient client = new MongoClient(host.ConnectionString); ...
- java 小程序开发PKCS7Padding 解密方法实现,以及错误Cannot find any provider supporting AES/CBC/PKCS7Padding 解决办法
近日在对接小程序API,其中wx.getUserInfo api返回的数据encryptedData 的解密算法要求为: AES-128-CBC,数据采用PKCS#7填充. 经过一番查询,得到java ...
- cache 缓存的处理
, ) { ? ? ) && ? lstorage.remove(key) : sstorage.remove(key) } /** * 更新缓存配置文件 */ Cache.proto ...
- js单元测试
最近研究了js的单元测试,分享一下心得. 说起单元测试以前还真是不太了解,这次索性了解一番,测试有很多包含单元测试,性能测试,安全测试和功能测试等几方面,本次只介绍一下单元测试. 前端进行单元测试主要 ...
- Linux下PHP扩展pdo_mysql
1.进入PHP源码包ext/pdo目录 cd ext/pdo 2.执行/usr/local/php/bin/phpize[假设PHP的安装目录为/usr/local/php] /usr/local/p ...