///<summary>
///DataRow转换成实体
///</summary>
///<paramname="DataRow">DataRow</param>
public static T ToModel<T>(DataRow row) where T : new()
{
if (row == null)
{
return default(T);
}
T t = new T();
PropertyInfo[] objPropertiesArray = t.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo objProperty in objPropertiesArray)
{
string value = string.Empty;
object val = null;
string Name = objProperty.Name;
int count = row.Table.Columns.Count;
for (int i = 0; i < count; i++)
{
if (Name.Equals(row.Table.Columns[i].ColumnName))
{
val = row[Name];
if (val != DBNull.Value)
{
objProperty.SetValue(t, Ct(val, objProperty.PropertyType), null);
}
break;
}
}
}
return t;
}
public static List<T> ToModelList<T>(DataTable dt) where T : new()
{
List<T> lstT = new List<T>();
foreach (DataRow row in dt.Rows)
{
lstT.Add(ToModel<T>(row));
}
return lstT;
}
/// <summary>
/// 处理Convert.ChangeType无法直接转换的类型,如:int?等
/// </summary>
/// <param name="value">待转换的值</param>
/// <param name="conversionType">实体属性类型</param>
/// <returns>转换后的类型</returns>
public static object Ct(object value, Type conversionType)
{
if (conversionType == null)
{
throw new ArgumentNullException("conversionType");
}
if (conversionType.IsGenericType &&
conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null)
{
return null;
}
NullableConverter nullableConverter = new NullableConverter(conversionType);
conversionType = nullableConverter.UnderlyingType;
}
if (value is string && conversionType == typeof(Guid))
{
return new Guid(value as string);
}
return Convert.ChangeType(value, conversionType);
}