码迷,mamicode.com
首页 > Web开发 > 详细

反射 DataTable拓展方法 转实体对象、实体集合、JSON

时间:2015-10-02 17:18:43      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

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);
        }
    }
}
View Code 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 > 0)
            {
                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 > 0)
                return Mapper.ToEntity<T>(table.Rows[0]);
            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>0)//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);
            }
        }
    }
}
View Code

 

反射 DataTable拓展方法 转实体对象、实体集合、JSON

标签:

原文地址:http://www.cnblogs.com/qingrp-2015930/p/4852317.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!