Mapper类

using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace CommonHelper
{
public class Mapper
{
public static object ToEntity(DataRow adaptedRow, Type entityType)
{
if (entityType == null || adaptedRow == null)
return null;
object entity = Activator.CreateInstance(entityType);
CopyToEntity(entity, adaptedRow);
return entity;
} public static T ToEntity<T>(DataRow adaptedRow) where T : new()
{
T item = new T();
if (adaptedRow == null)
return item;
item = Activator.CreateInstance<T>();
CopyToEntity(item, adaptedRow);
return item;
} public static void CopyToEntity(object entity, DataRow adaptedRow)
{
if (entity == null || adaptedRow == null)
return;
PropertyInfo[] propertyInfos = entity.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
if (!CanSetPropertyValue(propertyInfo, adaptedRow))
continue; try
{
if (adaptedRow[propertyInfo.Name] is DBNull)
{
propertyInfo.SetValue(entity, null, null);
continue;
}
SetPropertyValue(entity, adaptedRow, propertyInfo);
}
finally
{
}
}
} public static bool CanSetPropertyValue(PropertyInfo propertyInfo, DataRow adaptedRow)
{
if (!propertyInfo.CanWrite)
return false; if (!adaptedRow.Table.Columns.Contains(propertyInfo.Name))
return false; return true;
} public static void SetPropertyValue(object entity, DataRow adaptedRow, PropertyInfo propertyInfo)
{
if (propertyInfo.PropertyType == typeof(DateTime?) || propertyInfo.PropertyType == typeof(DateTime))
{
DateTime date = DateTime.MaxValue;
DateTime.TryParse(adaptedRow[propertyInfo.Name].ToString(),
CultureInfo.CurrentCulture, DateTimeStyles.None, out date); propertyInfo.SetValue(entity, date, null);
}
else
propertyInfo.SetValue(entity, adaptedRow[propertyInfo.Name], null);
}
}
}

mapper.cs

DataTable拓展方法

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace CommonHelper.Extensions
{
/// <summary>
/// DataTable拓展方法
/// </summary>
public static class DateTableExtensions
{
/// <summary>
/// 将dataTable转换为实体类集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <returns></returns>
public static List<T> ToCollection<T>(this DataTable table) where T : new()
{
if (table != null && table.Rows.Count > )
{
List<T> list = new List<T>();
foreach (DataRow dr in table.Rows)
{
list.Add(Mapper.ToEntity<T>(dr));
}
return list;
}
else
return new List<T>();
} /// <summary>
/// 将datattable第一行转换为实体类
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <returns></returns>
public static T FirstRowEntiy<T>(this DataTable table) where T :new()
{
if (table != null && table.Rows.Count > )
return Mapper.ToEntity<T>(table.Rows[]);
else
return default(T);
} /// <summary>
/// datatable转2标准Jon
/// </summary>
/// <param name="dt">DataTable数据源</param>
/// <param name="total">可选:转普通json传>0的值或忽略此参数;如果针对easyUI的json的一定要把total参数分页总行数传进来</param>
/// <returns></returns>
public static string ToJsonStr(this DataTable dt, int total)
{
System.Collections.ArrayList arrayList = new System.Collections.ArrayList();
foreach (DataRow dr in dt.Rows)
{
try
{
Dictionary<string, object> dictionary = new Dictionary<string, object>();//实例化一个参数集合
foreach (DataColumn column in dt.Columns)
{
dictionary.Add(column.ColumnName,dr[column.ColumnName].ToString();
}
arrayList.Add(dictionary);//arrarylist中添加键值
}
catch (Exception)
{ throw;
}
}
if (total>)//easyUI专用,分页的总行数
{
var dirctionary=new Dictionary<string,object>();
dirctionary.Add("total",total);//此参数是easyUI使用
dirctionary.Add("rows",arrayList);//此参数是easyUI使用
return JsonConvert.SerializeObject(dirctionary);//序列化参数
}
else
{
return JsonConvert.SerializeObject(arrayList);
}
}
}
}

反射 DataTable拓展方法 转实体对象、实体集合、JSON的更多相关文章

  1. C#实体对象序列化成Json并让字段的首字母小写的两种解决方法

    引言:最近在工作中遇到与某些API对接的post的数据需要将对象的字段首字母小写.解决办法有两种:第一种:使用对象的字段属性设置JsonProperty来实现(不推荐,因为需要手动的修改每个字段的属性 ...

  2. 将form表单元素转为实体对象 或集合 -ASP.NET C#

    简介: 做WEBFROM开发的同学都知道后台接收参数非常麻烦 虽然MVC中可以将表单直接转为集实,但不支持表单转为 LIST<T>这种集合 单个对象的用法: 表单: <input n ...

  3. C#实体对象序列化成Json,并让字段的首字母小写

    引言:最近在工作中遇到与某些API对接的post的数据需要将对象的字段首字母小写.解决办法有两种:第一种:使用对象的字段属性设置JsonProperty来实现(不推荐,因为需要手动的修改每个字段的属性 ...

  4. C#实体对象序列化成Json,格式化,并让字段的首字母小写

    解决办法有两种:第一种:使用对象的字段属性设置JsonProperty来实现(不推荐,因为需要手动的修改每个字段的属性) public class UserInfo { [JsonProperty(& ...

  5. C#调用webservice 时如何传递实体对象

    在webservice端公开一个实体类,然后实例化,赋值,然后再给到webservice,可以实现,但是,即使调用端和service端的实体类完全一致,你也要重新实例化service端的,重新赋值,将 ...

  6. EBS OAF开发中实体对象和视图对象的属性设置器

    EBS OAF开发中实体对象和视图对象的属性设置器 (版权声明.本人原创或者翻译的文章如需转载,如转载用于个人学习,请注明出处:否则请与本人联系,违者必究) 源文: Home > Oracle ...

  7. 利用java反射将结果集封装成为对象和对象集合

    java反射机制是什么 反射机制是在运行状态中,可以知道任何一个类的属性和方法,并且调用类的属性和方法: 反射机制能够做什么 1.判断运行对象的所属类 2.构造任意一个类的对象 3.获取任意一个类的属 ...

  8. 使用jackson工具类把对象或集合转为JSON格式

    jackson使用方法: 1.加入jar包: jackson-annotations-2.2.2.jar jackson-core-2.2.2.jar jackson-databind-2.2.2.j ...

  9. DataTable转换为Model实体对象

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

随机推荐

  1. NIO组件Selector详解

    Selector(选择器)是Java NIO中能够检测一到多个NIO通道,并能够知晓通道是否为诸如读写事件做好准备的组件.这样,一个单独的线程可以管理多个channel,从而管理多个网络连接. 下面是 ...

  2. Day 4 @ RSA Conference Asia Pacific & Japan 2016

    09.00 – 09.45 hrs Advanced Malware and the Cloud: The New Concept of 'Attack Fan-out' Krishna Naraya ...

  3. How to easily concatenate text based on criteria in Excel? 如何将Excel中的文本按条件合并

    To combine text with the unique ID numbers, you can extract the unique values first and then create ...

  4. DragQueryFile

    附件:http://files.cnblogs.com/xe2011/CSharp_DragQueryFile.rar using System.Runtime.InteropServices; th ...

  5. PHPExcel的读取excel的操作

    首先导入类库: require_once 'PHPExcel.php'; require_once 'PHPExcel\IOFactory.php'; require_once 'PHPExcel\R ...

  6. 15分钟弄懂 const 和 #define

    什么是const ? 什么是#define? 他们有什么用? 他们有什么区别? 应该怎么用? 总结 1. 什么是const ? const是C/C++中的一个关键字(修饰符), const一般用来定义 ...

  7. 墙裂推荐 iOS 资源大全

    这是个精心编排的列表,它包含了优秀的 iOS 框架.库.教程.XCode 插件.组件等等. 这个列表分为以下几个部分:框架( Frameworks ).组件( Components ).测试( Tes ...

  8. VC++中 wstring和string的互相转换实现

    在VC++开发中,经常会用到string和wstring,这就需要二者之间的转换,项目中封装了wstring和string相互转换的2个函数,实现如下: //将wstring转换成string std ...

  9. RedHat7安装Sublime Text 3

    下载Sublime Text 3 # wget http://c758482.r82.cf2.rackcdn.com/sublime_text_3_build_3083_x64.tar.bz2 解压S ...

  10. POJ-3278(BFS)

    题目:                                                                                                 ...