datatable转换为list<model> 映射

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;

namespace PORM.Data
{
    /// <summary>
    /// 常用映射关系帮助类
    /// </summary>
    public class CommonMap
    {
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dReader"></param>
        /// <returns></returns>
        public static IEnumerable<T> MapToIEnumerable<T>(IDataReader dReader) where T : class
        {
            using (dReader)
            {
                List<string> drFields = new List<string>(dReader.FieldCount);
                for (int i = 0; i < dReader.FieldCount; i++)
                {
                    drFields.Add(dReader.GetName(i).ToLower());
                }
                while (dReader.Read())
                {
                    T model = Activator.CreateInstance<T>();
                    foreach (PropertyInfo pi in model.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance))
                    {
                        if (drFields.Contains(pi.Name.ToLower()))
                        {
                            if (pi.PropertyType.IsEnum)
                            {
                                object enumName = Enum.ToObject(pi.PropertyType, pi.GetValue(model, null));
                                pi.SetValue(model, enumName, null);
                            }
                            else
                            {
                                if (!IsNullOrEmptyOrDBNull(dReader[pi.Name]))
                                {
                                    pi.SetValue(model, MapNullableType(dReader[pi.Name], pi.PropertyType), null);
                                }
                            }
                        }
                    }
                    yield return model;
                }
            }

        }

        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <returns></returns>
        public static IEnumerable<T> MapToIEnumerable<T>(DataTable table) where T : class
        {
            foreach (DataRow row in table.Rows)
            {
                yield return MapToModel<T>(row);
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dReader"></param>
        /// <returns></returns>
        public static T MapToModel<T>(IDataReader dReader) where T : class
        {
            using (dReader)
            {
                if (dReader.Read())
                {
                    List<string> drFields = new List<string>(dReader.FieldCount);
                    for (int i = 0; i < dReader.FieldCount; i++)
                    {
                        drFields.Add(dReader.GetName(i).ToLower());
                    }
                    T model = Activator.CreateInstance<T>();
                    foreach (PropertyInfo pi in model.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance))
                    {
                        if (drFields.Contains(pi.Name.ToLower()))
                        {
                            if (pi.PropertyType.IsEnum)
                            {
                                object enumName = Enum.ToObject(pi.PropertyType, pi.GetValue(model, null));
                                pi.SetValue(model, enumName, null);
                            }
                            else
                            {
                                if (!IsNullOrEmptyOrDBNull(dReader[pi.Name]))
                                {
                                    pi.SetValue(model, MapNullableType(dReader[pi.Name], pi.PropertyType), null);
                                }
                            }
                        }
                    }
                    return model;
                }
            }
            return default(T);
        }

        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dRow"></param>
        /// <returns></returns>
        public static T MapToModel<T>(DataRow dRow) where T : class
        {
            try
            {
                List<string> drItems = new List<string>(dRow.ItemArray.Length);
                for (int i = 0; i < dRow.ItemArray.Length; i++)
                {
                    drItems.Add(dRow.Table.Columns[i].ColumnName.ToLower());
                }
                T model = Activator.CreateInstance<T>();
                foreach (PropertyInfo pi in model.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance))
                {
                    if (drItems.Contains(pi.Name.ToLower()))
                    {
                        if (pi.PropertyType.IsEnum) //属性类型是否表示枚举
                        {
                            object enumName = Enum.ToObject(pi.PropertyType, pi.GetValue(model, null));
                            pi.SetValue(model, enumName, null); //获取枚举值,设置属性值
                        }
                        else
                        {
                            if (!IsNullOrEmptyOrDBNull(dRow[pi.Name]))
                            {
                                pi.SetValue(model, MapNullableType(dRow[pi.Name], pi.PropertyType), null);
                            }
                        }
                    }
                }
                return model;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="value"></param>
        /// <param name="mType"></param>
        /// <returns></returns>
        public static object MapNullableType(object value, Type mType)
        {
            if (mType.IsGenericType && mType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                if (IsNullOrEmptyOrDBNull(value))
                    return null;
                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(mType);
                mType = nullableConverter.UnderlyingType;
            }
            if (mType == typeof(bool) || mType == typeof(Boolean))
            {
                if (value is string)
                {
                    if (value.ToString() == "1")
                        return true;
                    else
                        return false;
                }
            }
            if (mType.IsEnum) //属性类型是否表示枚举
            {
                int intvalue;
                if (int.TryParse(value.ToString(), out intvalue))
                    return Enum.ToObject(mType, Convert.ToInt32(value));
                else
                    return System.Enum.Parse(mType, value.ToString(), false);
            }
            return Convert.ChangeType(value, mType);
        }

        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T MapType<T>(object value)
        {
            Type type = typeof(T);
            if (CommonMap.IsNullOrEmptyOrDBNull(value))
                value = type.IsValueType ? Activator.CreateInstance(type) : null;
            if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                try
                {
                    return (T)Convert.ChangeType(value, type.GetGenericArguments()[0]);
                }
                catch
                {
                    value = null;
                    return (T)value;
                }
            }
            if (type.IsEnum)
                return (T)Enum.ToObject(type, value);
            return (T)Convert.ChangeType(value, typeof(T));
        }

        /// <summary>
        /// 判断null或DBNull或空字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool IsNullOrEmptyOrDBNull(object obj)
        {
            return ((obj is DBNull) || obj == null || string.IsNullOrEmpty(obj.ToString())) ? true : false;
        }

    }
}

   List<UnCompareDrug> t = CommonMap.MapToIEnumerable<UnCompareDrug>(dt).ToList();

datatable转换为list<model>

时间: 2024-11-08 20:08:25

datatable转换为list<model> 映射的相关文章

DataTable转换为List&lt;Model&gt;的通用类

在开发中,把查询结果以DataTable返回很方便,但是在检索数据时又很麻烦,没有模型类型检索方便. 所以很多人都是按照以下方式做的: // 获得查询结果DataTable dt = DbHelper.ExecuteDataTable(...);// 把DataTable转换为IList<UserInfo>IList<UserInfo> users = ConvertToUserInfo(dt); 问题:如果此系统有几十上百个模型,那不是每个模型中都要写个把DataTable转换为

Datatable转换为Json 然后把Json数据放入 js 文件中

C#中把Datatable转换为Json的5个代码实例 /// <summary> /// Datatable转换为Json /// </summary> /// <param name="table">Datatable对象</param> /// <returns>Json字符串</returns> public static string ToJson(DataTable dt) { StringBuilde

DataTable转换为List&lt;T&gt;或者DataRow转换为T

这段时间开发ASP.NETMVC应用程序,从数据库获取数据之后,需要把记录转换为数据集在视图中显示.我们需要把DataTable转换为List<T>或者DataRow转换为T. 本篇中可以学习到相关的知识,数据库方面,创建表,添加数据,存储过程等.MVC方面,创建model,创建Entity,Utility写在一个目录中,控制器创建视图操作,以及行为操作. 先从数据库: SQL代码: CREATE TABLE [dbo].[Cookbook] ( [ID] INT IDENTITY(1,1)

DataTable转List&lt;Model&gt;通用类

/// <summary> /// DataTable转List<Model>通用类[实体转换辅助类] /// </summary> public class ModelConvertHelper<T> where T : new() { public static IList<T> ConvertToModel(DataTable dt) { // 定义集合 IList<T> ts = new List<T>(); //

将DataTable转换为List,将List转换为DataTable的实现类

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Xmh.DBUnit { /// <summary> /// 将DataTable转换为List,将

第二篇:Entity Framework CodeFirst &amp; Model 映射

小分享:我有几张阿里云优惠券,用券购买或者升级阿里云相应产品最多可以优惠五折!领券地址:https://promotion.aliyun.com/ntms/act/ambassador/sharetouser.html?userCode=ohmepe03 前一篇 第一篇:Entity Framework 简介 我有讲到,ORM 最关键的 Mapping,也提到了最早实现Mapping的技术,就是 特性 + 反射,那Entity Framework 实现Mapping 又是怎样的呢? Entity

C#中把Datatable转换为Json的5个代码实例

一. /// <summary> /// Datatable转换为Json /// </summary> /// <param name="table">Datatable对象</param> /// <returns>Json字符串</returns> public static string ToJson(DataTable dt) { StringBuilder jsonString = new String

DataTable转换为List

/// <summary> /// 利用反射将DataTable转换为List<T>对象 /// </summary> /// <param name="dt">DataTable 对象</param> /// <returns>List<T>集合</returns> public static List<T> DataTableToList<T>(DataTable

使用扩展方法将DataTable转换为List&lt;T&gt;

在将DataTable转换为List<T>时,找到了网上的方案,原文链接:http://stackoverflow.com/questions/4593663/fetch-datarow-to-c-sharp-object. 使用时,遇到DbNull无法正常转换的问题,所以做了修正补充,继续发代码上来. 欢迎补充修正. using System; using System.Collections.Generic; using System.Linq; using System.Data; us