实体类转DataTable

原创
03/29 15:25
阅读数 99

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data;

using System.Reflection;

namespace Util {

public class ConvertHelperUtils {

    /// <summary>
    /// 根据接口中的DtoInfo生成DataTable
    /// </summary>
    /// <typeparam name="TInterfaceObjInfo">本接口中的DtoInfo</typeparam>
    /// <param name="objInfoList">DtoInfo</param>
    /// <returns>DataTable</returns>
    internal static DataTable CreateTable<TInterfaceObjInfo>()
    {
        Type objType = typeof(TInterfaceObjInfo);
        DataTable dtResult = new DataTable();
        // 获取该模板类的所有属性.
        PropertyInfo[] pis = objType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
        if (pis == null)
        {
            return dtResult;
        }
        foreach (PropertyInfo pi in pis)
        {
            // 获取名为DataField的反射.
            object[] list = pi.GetCustomAttributes(typeof(DataFieldAttribute), true);
            if (list == null || list.Length <= 0)
            {
                continue;
            }
            if (!(list[0] is DataFieldAttribute))
            {
                continue;
            }
            string fieldName = ((DataFieldAttribute)list[0]).Name;
            if (!dtResult.Columns.Contains(fieldName))
            {
                Type type;//= typeof(object);
                if(pi.PropertyType.Equals(typeof(Nullable<double>)))
                {
                    type = typeof(double);
                }
                else if (pi.PropertyType.Equals(typeof(Nullable<float>)))
                {
                    type = typeof(float);
                }
                else if (pi.PropertyType.Equals(typeof(Nullable<long>)))
                {
                    type = typeof(long);
                }
                else if (pi.PropertyType.Equals(typeof(Nullable<ulong>)))
                {
                    type = typeof(ulong);
                }
                else if (pi.PropertyType.Equals(typeof(Nullable<int>)))
                {
                    type = typeof(int);
                }
                else if (pi.PropertyType.Equals(typeof(Nullable<uint>)))
                {
                    type = typeof(uint);
                }
                else if (pi.PropertyType.Equals(typeof(Nullable<decimal>)))
                {
                    type = typeof(decimal);
                }
                else if (pi.PropertyType.Equals(typeof(Nullable<bool>)))
                {
                    type = typeof(bool);
                }
                else if (pi.PropertyType.Equals(typeof(Nullable<char>)))
                {
                    type = typeof(char);
                }
                else if (pi.PropertyType.Equals(typeof(Nullable<byte>)))
                {
                    type = typeof(byte);
                }
                else
                {
                    type = pi.PropertyType;
                }
                dtResult.Columns.Add(fieldName, type);
            }

        }

        return dtResult;



    }
    /// <summary>
    /// 将DataRow转成指定的实体
    /// </summary>
    /// <typeparam name="TObject">实体类</typeparam>
    /// <param name="srcDr">DataRow</param>
    /// <returns>实体类</returns>
    private static  TObject MappingOne<TObject>(DataRow srcDr)
    {
        if (srcDr == null)
        {
            throw new Neusoft.Dawn.Core.Exceptions.ValueNullException("DataRow is NULL!");
        }
        TObject result = Activator.CreateInstance<TObject>();
        Type objType = typeof(TObject);
        // 获取该模板类的所有属性.
        PropertyInfo[] pis = objType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
        if (pis == null)
        {
            return result;
        }
        foreach (PropertyInfo pi in pis)
        {
            // 获取名为DataField的反射.
            object[] list = pi.GetCustomAttributes(typeof(DataFieldAttribute), true);
            if (list == null || list.Length <= 0)
            {
                continue;
            }
            if (!(list[0] is DataFieldAttribute))
            {
                continue;
            }
            string fieldName = ((DataFieldAttribute)list[0]).Name;
            if (srcDr.Table.Columns.Contains(fieldName))
            {
                if (srcDr[fieldName] == System.DBNull.Value)
                {
                    // 表数据为空
                    pi.SetValue(result, null, null);
                }
                else
                {
                    // 映射的数据表存在与之对应的列, 将该数据表值取出赋于类属性.
                    // 列与属性数据类型相同
                    // 
                    Type type ;//= typeof(object);
                    if (pi.PropertyType.Equals(typeof(Nullable<double>)))
                    {
                        type = typeof(double);
                    }
                    else if (pi.PropertyType.Equals(typeof(Nullable<float>)))
                    {
                        type = typeof(float);
                    }
                    else if (pi.PropertyType.Equals(typeof(Nullable<long>)))
                    {
                        type = typeof(long);
                    }
                    else if (pi.PropertyType.Equals(typeof(Nullable<ulong>)))
                    {
                        type = typeof(ulong);
                    }
                    else if (pi.PropertyType.Equals(typeof(Nullable<int>)))
                    {
                        type = typeof(int);
                    }
                    else if (pi.PropertyType.Equals(typeof(Nullable<uint>)))
                    {
                        type = typeof(uint);
                    }
                    else if (pi.PropertyType.Equals(typeof(Nullable<decimal>)))
                    {
                        type = typeof(decimal);
                    }
                    else if (pi.PropertyType.Equals(typeof(Nullable<bool>)))
                    {
                        type = typeof(bool);
                    }
                    else if (pi.PropertyType.Equals(typeof(Nullable<char>)))
                    {
                        type = typeof(char);
                    }
                    else if (pi.PropertyType.Equals(typeof(Nullable<byte>)))
                    {
                        type = typeof(byte);
                    }
                    else
                    {
                        type = pi.PropertyType;
                    }
                    if (srcDr.Table.Columns[fieldName].DataType == type)
                    {
                        // 直接将对应列的值赋给类属性
                        pi.SetValue(result, srcDr[fieldName], null);
                    }
                }
            }
        }

        return result;
    }
    /// <summary>
    /// 将Datatable转成IList
    /// </summary>
    /// <typeparam name="TObject">要转换的实体类型</typeparam>
    /// <param name="table">数据源</param>
    /// <returns>实体集合TObject</returns>
    public static  IList<TObject> ConvertToModel<TObject>(DataTable table)
    {
        IList<TObject> result = new List<TObject>();
        if (table == null)
        {
            return result;
        }
        foreach (DataRow srcDr in table.Rows)
        {
            try
            {
                TObject obj = MappingOne<TObject>(srcDr);
                result.Add(obj);
            }

            catch
            {
                throw;
            }
        }
        return result;
    }

    /// <summary>
    /// 将IList转成DataTable
    /// *TObject中的属性必须添加DataField特性
    /// </summary>
    /// <typeparam name="TObject">TObject</typeparam>
    /// <param name="objList">TObject数据集</param>
    /// <returns>DataTable</returns>
    public static DataTable ConvertToDataTable<TObject>(IList<TObject> objList)
    {
      
        //根据TObject生成DataTable
        DataTable dt = CreateTable<TObject>();
        foreach (TObject obj in objList)
        {
            DataRow dr = dt.NewRow();
            dt.Rows.Add(SetDataRow(dr, obj));
        }
        return dt;

    }
    /// <summary>
    ///  将实体类转成DataRow
    /// </summary>
    /// <typeparam name="TObject">实体类</typeparam>
    /// <param name="dr">DataRow</param>
    /// <param name="obj">实体类</param>
    /// <returns>DataRow</returns>
    private static DataRow SetDataRow<TObject>(DataRow dr, TObject obj)
    {

        Type t = obj.GetType();//取得实体类类型信息
        //取得实体类中所有公共属性信息集合
        System.Reflection.PropertyInfo[] pis = t.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
        if (pis == null)
        {//属性取得失败。
            StringBuilder msg = new StringBuilder();
            msg.Append("属性信息取得失败!");
            msg.Append(t.FullName);
            msg.Append("该实体中没有公共成员属性信息!");
            throw new Neusoft.Dawn.Core.Exceptions.ValueException(msg.ToString() );
        }
        foreach (System.Reflection.PropertyInfo pi in pis)
        {
            object[] list = pi.GetCustomAttributes(typeof(DataFieldAttribute), true);
            if (list == null || list.Length <= 0)
            {
                continue;
            }
            if (!(list[0] is DataFieldAttribute))
            {
                continue;
            }
            string fieldName = ((DataFieldAttribute)list[0]).Name;

            object value = pi.GetValue(obj, null);
            if (pi.PropertyType.Equals(typeof(string)))
            {
                value = value ?? string.Empty;//(value == null) ? string.Empty : value;
            }
            else
            {
                value = value ?? DBNull.Value; //(value == null) ? DBNull.Value : value;
            }
            dr[fieldName] = value;
        }
        return dr;
    }
}

}

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部