datatable 和实体互转

public static class ModelConvertHelper<T> where T : class,new()
{
public static List<T> DataTableToModel(DataTable table)
{
List<T> ts = new List<T>();

foreach (DataRow dr in table.Rows)
{
T t = new T();
// 获得此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
var tempName = pi.Name;
if (table.Columns.Contains(tempName))
{
// 判断此属性是否有Setter
if (!pi.CanWrite) continue;

object value = dr[tempName];
if (value != DBNull.Value)
{
pi.SetValue(t, value, null);
}
else
{
switch (pi.PropertyType.ToString())
{
case "System.Decimal": pi.SetValue(t, 0, null);
break;
case "System.DataTime": pi.SetValue(t, "1900/7/2", null);
break;
case "System.String": pi.SetValue(t, "", null);
break;
default: pi.SetValue(t, 0, null);
break;
}

}

}
}
ts.Add(t);
}
return ts;
}

/// <summary>
/// DataTableToEntityList
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> DataTableToEntityList(DataTable dt)
{
List<T> entiyList = new List<T>();

Type entityType = typeof(T);
PropertyInfo[] entityProperties = entityType.GetProperties();
try
{
foreach (DataRow row in dt.Rows)
{
T entity = Activator.CreateInstance<T>();

foreach (PropertyInfo propInfo in entityProperties)
{
if (dt.Columns.Contains(propInfo.Name))
{
if (!row.IsNull(propInfo.Name))
{
if ((propInfo.PropertyType.Name == "Nullable`1") && (propInfo.PropertyType.FullName.Contains("System.DateTime")))
{
propInfo.SetValue(entity, Convert.ChangeType(row[propInfo.Name], typeof(DateTime)), null);
}
else if ((propInfo.PropertyType.Name == "Nullable`1") && (propInfo.PropertyType.FullName.Contains("System.Guid")))
{
propInfo.SetValue(entity, Convert.ChangeType(row[propInfo.Name], typeof(Guid)), null);
}
else if (propInfo.PropertyType.FullName.Contains("System.Decimal"))
{
if (row[propInfo.Name] != DBNull.Value && row[propInfo.Name].ToString() != "")
{
propInfo.SetValue(entity, Convert.ChangeType(row[propInfo.Name], typeof(decimal)), null);
}
else
{
propInfo.SetValue(entity, Decimal.Parse("0"));
}
}
else
{
propInfo.SetValue(entity, Convert.ChangeType(row[propInfo.Name], propInfo.PropertyType), null);
}
}
else
{
if (propInfo.PropertyType.FullName.Contains("System.String"))
{
propInfo.SetValue(entity, "");
}
}
}
}

entiyList.Add(entity);
}
}
catch (Exception ex)
{
string a = ex.Message.ToString();
throw ex;
}

return entiyList;
}

public static List<T> DataTableToEntityListIgnoreType(DataTable dt)
{
List<T> entiyList = new List<T>();

Type entityType = typeof(T);
PropertyInfo[] entityProperties = entityType.GetProperties();
try
{
foreach (DataRow row in dt.Rows)
{
T entity = Activator.CreateInstance<T>();

foreach (PropertyInfo propInfo in entityProperties)
{
if (dt.Columns.Contains(propInfo.Name))
{
if (!row.IsNull(propInfo.Name))
{
propInfo.SetValue(entity, row[propInfo.Name], null);
}
else
{
if (propInfo.PropertyType.FullName.Contains("System.String"))
{
propInfo.SetValue(entity, "");
}
}
}
}

entiyList.Add(entity);
}
}
catch (Exception ex)
{
throw ex;
}

return entiyList;
}

/// <summary>
/// datatable => model
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static T DataTableToEntity(DataTable dt)
{
try
{
if (dt.Rows.Count <= 0) return default(T);
DataRow row = dt.Rows[0];

T entity = Activator.CreateInstance<T>();
Type entityType = typeof(T);
PropertyInfo[] entityProperties = entityType.GetProperties();

foreach (PropertyInfo propInfo in entityProperties)
{
if (dt.Columns.Contains(propInfo.Name))
{
if (!row.IsNull(propInfo.Name))
{
if ((propInfo.PropertyType.Name == "Nullable`1") && (propInfo.PropertyType.FullName.Contains("System.DateTime")))
{
propInfo.SetValue(entity, Convert.ChangeType(row[propInfo.Name], typeof(DateTime)), null);
}
else if ((propInfo.PropertyType.Name == "Nullable`1") && (propInfo.PropertyType.FullName.Contains("System.Guid")))
{
propInfo.SetValue(entity, Convert.ChangeType(row[propInfo.Name], typeof(Guid)), null);
}
else if (propInfo.PropertyType.FullName.Contains("System.Decimal"))
{
propInfo.SetValue(entity, Convert.ChangeType(row[propInfo.Name], typeof(decimal)), null);
}
else
{
propInfo.SetValue(entity, Convert.ChangeType(row[propInfo.Name], propInfo.PropertyType), null);
}
}
}
else if (propInfo.PropertyType.Name == "String")
{
propInfo.SetValue(entity, string.Empty, null);
}
}
return entity;
}
catch (Exception ex)
{
throw ex;
}
}

#region 实体转换成DataTable
public static DataTable ModelConvertToTable(List<T> list)
{
T obj = list[0];
PropertyInfo[] propertys = obj.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
DataTable table = new DataTable();
foreach (var property in propertys)
{
table.Columns.Add(property.Name);
}
foreach (T item in list)
{
DataRow row = table.NewRow();
foreach (var property in propertys)
{
if (table.Columns.Contains(property.Name))
{
row[property.Name] = property.GetValue(item, null) == null ? DBNull.Value : property.GetValue(item, null);
}
}
table.Rows.Add(row);
}
return table;
}

static List<Type> _bascType = new List<Type>() {
typeof(System.String),
typeof(System.Decimal),
typeof(System.Boolean),
typeof(System.Char),
typeof(System.Byte),
typeof(System.SByte),
typeof(System.Int16),
typeof(System.Int32),
typeof(System.Int64),
typeof(System.UInt16),
typeof(System.UInt32),
typeof(System.UInt64),
typeof(System.Single),
typeof(System.Double),
typeof(System.DateTime)

};

public static DataTable EntityToDataTableV2(List<T> entityList)
{
if (entityList == null || entityList.Count <= 0)
{
return null;
}
DataTable dt = new DataTable();
Type entityType = typeof(T);
PropertyInfo[] entityProperties = entityType.GetProperties();
Type colType = null;
foreach (PropertyInfo propInfo in entityProperties)
{
if (propInfo.PropertyType.IsGenericType)
{
colType = Nullable.GetUnderlyingType(propInfo.PropertyType);
}
else
{
colType = propInfo.PropertyType;
}
//if (colType.GetInterfaces().Contains(typeof(IComparable)))
if (_bascType.Contains(colType))
{
dt.Columns.Add(propInfo.Name, colType);
}
}
foreach (T entity in entityList)
{
DataRow newRow = dt.NewRow();
foreach (PropertyInfo propInfo in entityProperties)
{
if (dt.Columns.Contains(propInfo.Name))
{
object objValue = propInfo.GetValue(entity, null);
newRow[propInfo.Name] = objValue == null ? DBNull.Value : objValue;
}
}
dt.Rows.Add(newRow);
}
return dt;
}

public static DataTable EntityToDataTable(List<T> entityList)
{
if (entityList == null || entityList.Count <= 0)
{
return null;
}
DataTable dt = new DataTable();
Type entityType = typeof(T);
PropertyInfo[] entityProperties = entityType.GetProperties();
Type colType = null;
foreach (PropertyInfo propInfo in entityProperties)
{
if (propInfo.PropertyType.IsGenericType)
{
colType = Nullable.GetUnderlyingType(propInfo.PropertyType);
}
else
{
colType = propInfo.PropertyType;
}


if (colType.FullName.StartsWith("System"))
{
dt.Columns.Add(propInfo.Name, colType);
}
}
foreach (T entity in entityList)
{
DataRow newRow = dt.NewRow();
foreach (PropertyInfo propInfo in entityProperties)
{
if (dt.Columns.Contains(propInfo.Name))
{
object objValue = propInfo.GetValue(entity, null);
newRow[propInfo.Name] = objValue == null ? DBNull.Value : objValue;
}
}
dt.Rows.Add(newRow);
}
return dt;
}
#endregion
}

原文地址:https://www.cnblogs.com/muxueyuan/p/7442416.html