//将DataTable转为对象实体:T为数据类型
public static List<T> DataTableToObjects<T>(DataTable dt)
{
List<T> objList = new List<T>();
if (dt != null && dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
T obj = DataRowToObject<T>(dr);
objList.Add(obj);
}
}
return objList;
}
//将DataRow转换为对象实体:T为数据类型
public static T DataRowToObject<T>(DataRow dr)
{
T obj = Activator.CreateInstance<T>(); //先创建一个实体实例
//获取实体实例的属性信息
ArrayList propertyInfoList = new ArrayList();
foreach (PropertyInfo propInfo in obj.GetType().GetProperties())
{
propertyInfoList.Add(propInfo);
}
//遍历各个属性
for (int i = 0; i <= propertyInfoList.Count - 1; i++)
{
PropertyInfo propertyInfo = (PropertyInfo)propertyInfoList[i];
if (propertyInfo.CanWrite)
{
if (dr.Table.Columns.Contains(propertyInfo.Name))
{
if (dr[propertyInfo.Name] != DBNull.Value)
{
try
{
object dataValue = dr[propertyInfo.Name]; //数据行中的字段的值
object value = ConvertToPropertyValue(propertyInfo, dataValue); //将字段的值转换为属性值
propertyInfo.SetValue(obj, value, null);
}
catch
{
}
}
}
}
}
return obj;
}
//将数据行中的数据值转换为属性值
private static object ConvertToPropertyValue(PropertyInfo propInfo, object value)
{
try
{
//类型转换器的调用
object[] ormAtts = propInfo.GetCustomAttributes(typeof(ORMAttribute), false);
if (ormAtts.Length > 0)
{
Type cvType = ((ORMAttribute)ormAtts[0]).ConvertProvider;
if (cvType != null && cvType == typeof(ITypeConvertProvider))
{
object converter = Activator.CreateInstance(cvType);
return ((ITypeConvertProvider)converter).Convert(value);
}
}
//枚举类型转换
if (propInfo.PropertyType.IsEnum)
{
object returnValue = ORMEnumConverter.GetEnumValue(value.ToString(), propInfo.PropertyType);
if (returnValue == null)
{
returnValue = System.Enum.ToObject(propInfo.PropertyType, value);
}
return returnValue;
}
//枚举值泛型转换
if (propInfo.PropertyType.IsValueType && propInfo.PropertyType.IsGenericType)
{
if (typeof(Nullable<>) == propInfo.PropertyType.GetGenericTypeDefinition())
{
Type genericArg = propInfo.PropertyType.GetGenericArguments()[0];
if (genericArg.IsEnum)
{
object returnValue = ORMEnumConverter.GetEnumValue(value.ToString(), genericArg);
if (returnValue == null)
{
returnValue = System.Enum.ToObject(genericArg, value);
}
return returnValue;
}
return Convert.ChangeType(value, genericArg);
}
}
//对于GUID类型的处理
if (propInfo.PropertyType.FullName == "System.Guid")
{
if (value is byte[])
{
return new Guid((byte[])value);
}
else if (value is string)
{
return new Guid((string)value);
}
}
return Convert.ChangeType(value, propInfo.PropertyType);
}
catch
{
}
return null;
}