netnr / ToDataTable-ToModel.cs
2018-11-03 10:06

实体转表、表转实体

/// <summary>
/// 实体转表
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="list">对象</param>
/// <returns></returns>
public static DataTable ToDataTable<T>(this IList<T> list)
{
    Type elementType = typeof(T);
    var t = new DataTable();
    elementType.GetProperties().ToList().ForEach(propInfo => t.Columns.Add(propInfo.Name, Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType));
    foreach (T item in list)
    {
        var row = t.NewRow();
        elementType.GetProperties().ToList().ForEach(propInfo => row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value);
        t.Rows.Add(row);
    }
    return t;
}

/// <summary>
/// 表转为实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <returns></returns>
public static List<T> ToModel<T>(this DataTable table) where T : class, new()
{
    var list = new List<T>();
    foreach (DataRow dr in table.Rows)
    {
        var model = new T();
        foreach (DataColumn dc in dr.Table.Columns)
        {
            object drValue = dr[dc.ColumnName];

            var pi = model.GetType().GetProperties().Where(x => x.Name.ToLower() == dc.ColumnName.ToLower()).FirstOrDefault();

            Type type = pi.PropertyType;
            if (pi.PropertyType.FullName.Contains("System.Nullable"))
            {
                type = Type.GetType("System." + pi.PropertyType.FullName.Split(',')[0].Split('.')[2]);
            }

            if (pi != null && pi.CanWrite && (drValue != null && !Convert.IsDBNull(drValue)))
            {
                try
                {
                    drValue = Convert.ChangeType(drValue, type);
                    pi.SetValue(model, drValue, null);
                }
                catch (Exception)
                {

                }
            }
        }
        list.Add(model);
    }
    return list;
}
ˆ