利用反射将Datatable、SqlDataReader转换成List模型
1. DataTable转IList
public class DataTableToList<T>whereT :new() { ///<summary> ///利用反射将Datatable转换成List模型 ///</summary> ///<param name="dt"></param> ///<returns></returns> public static List<T> ConvertToList(DataTabledt) { List<T> list =newList<T>(); Typetype =typeof(T); stringtempName =string.Empty; foreach(DataRowdrindt.Rows) { T t =newT(); PropertyInfo[] propertys =
t.GetType().GetProperties(); foreach(PropertyInfopiinpropertys) { tempName = pi.Name; if(dt.Columns.Contains(tempName)) { if(!pi.CanWrite) { continue; } var value = dr[tempName]; if(value !=DBNull.Value) { pi.SetValue(t, value,null); } } } list.Add(t); } returnlist; } }
2. SqlDataReader转IList
/// <summary>
/// 判断SqlDataReader是否存在某列
/// </summary>
/// <param name="dr">SqlDataReader</param>
/// <param name="columnName">列名</param>
/// <returns></returns>
private bool readerExists(SqlDataReader dr, string columnName)
{ dr.GetSchemaTable().DefaultView.RowFilter = "ColumnName= '" + columnName + "'"; return (dr.GetSchemaTable().DefaultView.Count > ); } ///<summary>
///利用反射和泛型将SqlDataReader转换成List模型
///</summary>
///<param name="sql">查询sql语句</param>
///<returns></returns> public IList<T> ExecuteToList<T>(string sql) where T : new() {
IList<T> list; Type type = typeof (T); string tempName = string.Empty; using (SqlDataReader reader = ExecuteReader(sql))
{
if (reader.HasRows)
{
list = new List<T>();
while (reader.Read())
{
T t = new T(); PropertyInfo[] propertys = t.GetType().GetProperties(); foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name; if (readerExists(reader, tempName))
{
if (!pi.CanWrite)
{
continue;
}
var value = reader[tempName]; if (value != DBNull.Value)
{
pi.SetValue(t, value, null);
} } } list.Add(t); }
return list;
}
}
return null;
}
3、结果集从存储过程获取
/// <summary>
/// 处理存储过程
/// </summary>
/// <param name="spName">存储过程名</param>
/// <param name="parameters">参数数组</param>
/// <returns>sql数据流</returns>
protected virtual SqlDataReader ExecuteReaderSP(string spName, ArrayList parameters)
{
SqlDataReader result = null;
cmd.CommandText = spName;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
if (parameters != null)
{
foreach (SqlParameter param in parameters)
{
cmd.Parameters.Add(param);
}
}
try
{
Open();
result = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception e)
{
if (result != null && (!result.IsClosed))
{
result.Close();
}
LogHelper.WriteLog("\r\n方法异常【ExecuteReaderSP(string spName, ArrayList parameters)】" + spName, e);
throw new Exception(e.Message);
}
return result;
}
<strong> </strong> ///<summary>
///利用反射将SqlDataReader转换成List模型
///</summary>
///<param name="spName">存储过程名称</param>
///<returns></returns> public IList<T> ExecuteQueryListSP<T>(string spName, params SqlParameter[] listParams) where T : new()
{
IList<T> list; Type type = typeof(T); string tempName = string.Empty; using (SqlDataReader reader = ExecuteReaderSP(spName, new ArrayList(listParams)))
{
if (reader.HasRows)
{
list = new List<T>();
while (reader.Read())
{
T t = new T(); PropertyInfo[] propertys = t.GetType().GetProperties(); foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name; //for (int intField = 0; intField < reader.FieldCount; intField++)
//{//遍历该列名是否存在
//} if (readerExists(reader, tempName))
{
if (!pi.CanWrite)
{
continue;
}
var value = reader[tempName]; if (value != DBNull.Value)
{
pi.SetValue(t, value, null);
} } } list.Add(t); }
return list;
}
}
return null;
}
作者:dasihg
转载:http://blog.csdn.net/dasihg/article/details/8943811
利用反射将Datatable、SqlDataReader转换成List模型的更多相关文章
- 利用反射把数据集合转换成List
---ResultSet数据集 public static List toList(ResultSet rs, Class cls) { List list = new ArrayList(); tr ...
- C# 利用反射动态将字符串转换成属性对应的类型值
/// <summary> /// 为指定对象分配参数 /// </summary> /// <typeparam name="T">对象类型& ...
- C# 将DataTable数据源转换成实体类
using System; using System.Collections.Generic; using System.Data; using System.Reflection; /// < ...
- 利用反射把DataTable自动赋值到Model实体(自动识别数据类型)
转:http://www.cnblogs.com/the7stroke/archive/2012/04/22/2465591.html using System.Collections.Generic ...
- C 利用移位运算符 把十进制转换成二进制
#include <stdio.h> int main(void){ //利用移位运算符 把十进制转换成二进制 int c; printf("输入数字:");//8 s ...
- 「新手必看」Python+Opencv实现摄像头调用RGB图像并转换成HSV模型
在ROS机器人的应用开发中,调用摄像头进行机器视觉处理是比较常见的方法,现在把利用opencv和python语言实现摄像头调用并转换成HSV模型的方法分享出来,希望能对学习ROS机器人的新手们一点帮助 ...
- h5模型文件转换成pb模型文件
本文主要记录Keras训练得到的.h5模型文件转换成TensorFlow的.pb文件 #*-coding:utf-8-* """ 将keras的.h5的模型文件,转换 ...
- 【tensorflow-v2.0】如何将模型转换成tflite模型
前言 TensorFlow Lite 提供了转换 TensorFlow 模型,并在移动端(mobile).嵌入式(embeded)和物联网(IoT)设备上运行 TensorFlow 模型所需的所有工具 ...
- 利用反射实现DataTable 与 List<T> 转换
今天上班不太忙,就想着总结一下反射.扩展方法.以及lambda表达式的用法,自己就写了个小DEMO记录一下,希望各位大牛们看到后觉得不对的地方请及时提出.这篇文章中我只说明我的用法,作为一个备忘,基本 ...
随机推荐
- wex5 教程之 图文讲解 文件上传attachmentSimple(1)
视频教程地址:http://v.youku.com/v_show/id_XMTc4NDAyMTY4OA==.html 效果预览: 1 调用attchmentSimple组件,打开文件管理器,并选中,显 ...
- mysql 乱码问题
A.mysql设置 1.service mysql stop 2.sudo vim /etc/mysql/my.cnf 在[mysqld]中添加下面两行 character_set_server = ...
- lucene5.5 field
lucene常见Field IntField 主要对int类型的字段进行存储,需要注意的是如果需要对InfField进行排序使用SortField.Type.INT来比较,如果进范围查询或过滤,需要采 ...
- Popwindow
popwindow的使用方法 View contentView = LayoutInflater.from(mContext).inflate( R.layout.dialog_homelist_vi ...
- Zip it
https://www.codewars.com/kata/zip-it/train/csharp using System; using System.Collections.Generic; us ...
- How To Use FETCH_RECORDS In Oracle Forms
When called from an On-Fetch trigger, initiates the default Form Builder processing for fetching rec ...
- mysql 增删改查基本语句
增: insert insert into 表名(字段1,字段2,字段3......字段N) values(值1,值2,值3): 如果不申明插入那些字段,则默认所有字段. 在插入时注意,往哪个表增加, ...
- jquery mobile 和phonegap开发总结之三跨域加载页面
跨域加载 一要进行一定的配置见下面 $( document ).bind( "mobileinit", function() { // Make your jQuery Mobil ...
- js正则表达式入门
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/ ...
- M1卡介绍
本文整理自网络. M1卡是指菲利浦下属子公司恩智浦出品的芯片缩写,全称为NXP Mifare1系列,常用的有S50及S70两种型号,目前都有国产芯片与其兼容,属于非接触式IC卡.最为重要的优点是可读可 ...