代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Reflection;
/// <summary>
/// 将DataTable数据源转换成实体类
/// </summary>
public static class ConvertTool
{
/// <summary>
/// DataTable转换成实体类
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> TableToEntity<T>(DataTable dt) where T : class, new()
{
List<T> list = new List<T>();
try
{
foreach (DataRow row in dt.Rows)
{
T entity = new T();
PropertyInfo[] pArray = entity.GetType().GetProperties();
foreach (PropertyInfo p in pArray)
{
if (dt.Columns.Contains(p.Name))
{
if (!p.CanWrite) continue;
var value = row[p.Name];
if (value != DBNull.Value)
{
Type targetType = p.PropertyType;
Type convertType = targetType;
if (targetType.IsGenericType && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
//可空类型
NullableConverter nullableConverter = new NullableConverter(targetType);
convertType = nullableConverter.UnderlyingType;
}
if (!string.IsNullOrEmpty(convertType.FullName) && !string.IsNullOrEmpty(value.ToString()))
{
value = Convert.ChangeType(value, convertType);
}
switch (convertType.FullName)
{
case "System.Decimal":
p.SetValue(entity, Convert.ToDecimal(value), null);
break;
case "System.String":
p.SetValue(entity, Convert.ToString(value), null);
break;
case "System.Int32":
p.SetValue(entity, Convert.ToInt32(value), null);
break;
case "System.Int64":
p.SetValue(entity, Convert.ToInt64(value), null);
break;
case "System.Int16":
p.SetValue(entity, Convert.ToInt16(value), null);
break;
case "System.Double":
p.SetValue(entity, Convert.ToDouble(value), null);
break;
case "System.DateTime":
p.SetValue(entity, Convert.ToDateTime(value), null);
break;
default:
p.SetValue(entity, value, null);
break;
}
}
}
}
list.Add(entity);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
if(list.Count > 0)
return list;
else
return null;
}
}
end
|