C# DateTable与实体类的转换

/// <summary>    
/// 实体转换辅助类    
/// </summary>    
public static class ModelConvertHelper
{
    /// <summary>
    /// 转为List<T>
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static List<T> ToModelList<T>(this DataTable dt) where T : new()
    {
        // 定义集合    
        List<T> ts = new List<T>();

        // 获得此模型的类型   
        Type type = typeof(T);
        string tempName = null, tempDescription = null;

        foreach (DataRow dr in dt.Rows)
        {
            T t = new T();
            // 获得此模型的公共属性      
            PropertyInfo[] propertys = t.GetType().GetProperties();
            foreach (PropertyInfo pi in propertys)
            {
                // 检查DataTable是否包含此列    
                tempName = pi.Name;  
                tempDescription = pi == null ? null : ((DescriptionAttribute)Attribute.GetCustomAttribute(pi, typeof(DescriptionAttribute)))?.Description;
                string column = tempDescription ?? tempName;

                if (dt.Columns.Contains(column))
                {
                    // 判断此属性是否有Setter      
                    if (!pi.CanWrite)
                        continue;

                    object value = dr[column];

                    if (value != DBNull.Value)
                    {
                        if (pi.PropertyType.ToString().Contains("System.Nullable"))
                            value = Convert.ChangeType(value, Nullable.GetUnderlyingType(pi.PropertyType));
                        else
                            value = Convert.ChangeType(value, pi.PropertyType);
                        pi.SetValue(t, value, null);
                    }
                }
            }
            ts.Add(t);
        }
        return ts;
    }


    /// <summary>
    /// 将实体集合转换为DataTable
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="entities">实体集合</param>
    public static DataTable ToDataTable<T>(this IList<T> entities)
    {
        var result = CreateTable<T>();
        FillData(result, entities);
        return result;
    }

    /// <summary>
    /// 创建表
    /// </summary>
    private static DataTable CreateTable<T>()
    {
        var result = new DataTable();
        var type = typeof(T);
        foreach (var property in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
        {
            var propertyType = property.PropertyType;
            if ((propertyType.IsGenericType) && (propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                propertyType = propertyType.GetGenericArguments()[0];
            result.Columns.Add(property.Name, propertyType);
        }
        return result;
    }

    /// <summary>
    /// 填充数据
    /// </summary>
    private static void FillData<T>(DataTable dt, IEnumerable<T> entities)
    {
        foreach (var entity in entities)
        {
            dt.Rows.Add(CreateRow(dt, entity));
        }
    }

    /// <summary>
    /// 创建行
    /// </summary>
    private static DataRow CreateRow<T>(DataTable dt, T entity)
    {
        DataRow row = dt.NewRow();
        var type = typeof(T);
        foreach (var property in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
        {
            row[property.Name] = property.GetValue(entity) ?? DBNull.Value;
        }
        return row;
    }

    /// <summary>
    /// 转换为List<T>, 仅转一 列 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="dt"></param>
    /// <param name="column"></param>
    /// <returns></returns>
    public static List<T> ToSimpleList<T>(this DataTable dt, int column = 0)
    {
        // 定义集合    
        List<T> ts = new List<T>();
        foreach (DataRow dr in dt.Rows)
        {
            T t = (T)dr[column];
            ts.Add(t);
        }
        return ts;
    }
}

转载注明原文地址:https://www.cnblogs.com/Veary/p/14338096.html

posted @ 2021-01-28 09:36  Veary  阅读(286)  评论(0)    收藏  举报