DataRow映射实体

时间:2023-03-09 03:39:07
DataRow映射实体
 public static T ConvertToModel<T>(DataRow dr) where T : new()
{
T t = new T();
Type modelType = t.GetType();
foreach (PropertyInfo pi in modelType.GetProperties())
{
if (pi == null) continue;
if (pi.CanWrite == false) continue; if (dr.Table.Columns.Contains(pi.Name))
{
//p.SetValue(t, GetDefaultValue(dr[p.Name], p.PropertyType), null);
try
{
if (dr[pi.Name] != DBNull.Value)
pi.SetValue(t, dr[pi.Name], null);
else
pi.SetValue(t, default(object), null);
}
catch
{
pi.SetValue(t, GetDefaultValue(dr[pi.Name], pi.PropertyType), null);
}
} }
return t;
} private static object GetDefaultValue(object obj, Type type)
{
if (obj == DBNull.Value)
{
return default(object);
}
else
{
return Convert.ChangeType(obj, type);
}
}

  纯代码难得打字