Entity 属性和table字段对应,依靠反射属性赋值

private T Get<T>(DataRow dr) where T : new()
{
T myResult = Activator.CreateInstance<T>();
PropertyInfo[] properties = myResult.GetType().GetProperties();
foreach (var item in properties)
{
var columnName = item.Name.ToLower();
if (dr.Table.Columns.Contains(columnName))
{
object obj = null;
if (item.PropertyType.IsGenericType)
{
Type genericTypeDefinition = item.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
obj = dr[columnName] == DBNull.Value ? null : Convert.ChangeType(dr[columnName], Nullable.GetUnderlyingType(item.PropertyType));
}
}
else
{
if (item.PropertyType.FullName == "System.Guid")
{
obj = dr[columnName] == DBNull.Value ? Guid.Empty : Guid.Parse(dr[columnName].ToString());
}
else if (item.PropertyType.FullName == "System.String")
{
obj = dr[columnName] == DBNull.Value ? string.Empty : dr[columnName].ToString();
}
else
{
obj = dr[columnName] == DBNull.Value ? null : Convert.ChangeType(dr[columnName], item.PropertyType);
}
}
item.SetValue(myResult, obj);
}
}
return myResult;
}

猜你喜欢

转载自www.cnblogs.com/lrdbky/p/9560389.html