using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data;
using System.Reflection;
using System.Collections;
namespace Common.Model
{
///
/// 实体转换辅助类
///
public class ModelConvertHelper where T : new()
{
public static IList ConvertToModel(DataTable dt,bool IsDateTimeEmpty = false)
{
// 定义集合
IList ts = new List();
// 获得此模型的类型
Type type = typeof(T);
string tempName = "";
foreach (DataRow dr in dt.Rows)
{
T t = new T();
// 获得此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name; // 检查DataTable是否包含此列
if (dt.Columns.Contains(tempName))
{
// 判断此属性是否有Setter
if (!pi.CanWrite) continue;
object value = dr[tempName];
if (value != DBNull.Value)
{
//加一重if判断,如果属性值是int32类型的,就进行一次强制转换
if (pi.GetMethod.ReturnParameter.ParameterType.Name == "Int32")
{
value = Convert.ToInt32(value);
}
pi.SetValue(t, value, null);
}
if (IsDateTimeEmpty)
{
if (pi.PropertyType.ToString() == "System.DateTime")
{
if (value.ToString() == DateTime.MinValue.ToString())
{
pi.SetValue(t, value, null);
}
}
}
}
}
ts.Add(t);
}
return ts;
}
///
/// list转datatable
///
///
///
///
public DataTable ListToDt(IEnumerable collection)
{
var props = typeof(T).GetProperties();
var dt = new DataTable();
dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
if (collection.Count() > 0)
{
for (int i = 0; i < collection.Count(); i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in props)
{
object obj = pi.GetValue(collection.ElementAt(i), null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
dt.LoadDataRow(array, true);
}
}
return dt;
}
}
}