///
/// 实体转表
///
/// 泛型
/// 对象
///
public static DataTable ToDataTable(this IList 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;
}
///
/// 表转为实体
///
///
///
///
public static List ToModel(this DataTable table) where T : class, new()
{
var list = new List();
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;
}