/// <summary>
/// DataTable转换成实体列表
/// </summary>
/// <typeparam name="T">实体 T </typeparam>
/// <param name="table">datatable</param>
/// <returns></returns>
public static IList<T> DataTableToList<T>(DataTable table)
where T : class
{
if (!IsHaveRows(table))
return new List<T>();
IList<T> list = new List<T>();
T model = default(T);
foreach (DataRow dr in table.Rows)
{
model = Activator.CreateInstance<T>();
foreach (DataColumn dc in dr.Table.Columns)
{
object drValue = dr[dc.ColumnName];
PropertyInfo pi = model.GetType().GetProperty(dc.ColumnName.Trim());
if (pi != null && pi.CanWrite && drValue != null && !Convert.IsDBNull(drValue)&&!string.IsNullOrEmpty(drValue.ToString()))
{
if (pi.PropertyType == typeof(Guid))
{
pi.SetValue(model, Guid.Parse(drValue.ToString()), null);
}
else if (pi.PropertyType == typeof(Guid?))
{
pi.SetValue(model, Guid.Parse(drValue.ToString()), null);
}
else if (pi.PropertyType == typeof(NonWasteCellPointLevel)||pi.PropertyType == typeof(DeclareStatusEnum))
{
pi.SetValue(model, Enum.Parse(pi.PropertyType,drValue.ToString()), null);
}
else if (pi.PropertyType == typeof(bool)&&(drValue.ToString()!="true"||drValue.ToString()!="false"))
{
var value = int.Parse(drValue.ToString());
if ( value== 1)
{
pi.SetValue(model, true, null);
}
else
{
pi.SetValue(model, false, null);
}
}
else
{
object convertedValue = Convert.ChangeType(drValue, pi.PropertyType);
pi.SetValue(model, convertedValue, null);
}
}
}
list.Add(model);
}
return list;
}
/// <summary>
/// 实体列表转换成DataTable
/// </summary>
/// <typeparam name="T">实体</typeparam>
/// <param name="list"> 实体列表</param>
/// <returns></returns>
public static DataTable ListToDataTable<T>(IList<T> list)
where T : class
{
if (list == null || list.Count <= 0)
{
return null;
}
DataTable dt = new DataTable(typeof(T).Name);
DataColumn column;
DataRow row;
PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
bool createColumn = true;
foreach (T t in list)
{
if (t == null)
{
continue;
}
row = dt.NewRow();
for (int i = 0; i < myPropertyInfo.Length; i++)
{
PropertyInfo pi = myPropertyInfo[i];
if (createColumn)
{
column = new DataColumn(pi.Name,pi.PropertyType );
dt.Columns.Add(column);
}
row[pi.Name] = pi.GetValue(t, null);
}
if (createColumn)
{
createColumn = false;
}
dt.Rows.Add(row);
}
return dt;
}
如果提示 没有类型System.Nullable`1 错误,说明你在实体中定义字段时加上了?(可为空),比如 int? id ,此时就会报这个错。