您的位置:首页 > 其它

将DataTable转换为List<T>对象遇到问题:类型“System.Int64”的对象无法转换为类型“System.Int32”。

2017-07-18 11:29 721 查看
报错信息:

将DataTable转换为List<T>对象遇到问题,类型“System.Int64”的对象无法转换为类型“System.Int32”。



解决方案:

以下红色为新添加的,单独判断下Int32,然后强转一次

/// <summary>
/// DataTable转List
/// </summary>
/// <typeparam name="T"></typeparam>
public class ModelConvertHelper<T> where T : new()  // 此处一定要加上new()
{
public static IList<T> ConvertToModel(System.Data.DataTable dt)
{

IList<T> ts = new List<T>();// 定义集合
Type type = typeof(T); // 获得此模型的类型
string tempName = "";
foreach (System.Data.DataRow dr in dt.Rows)
{
T t = new T();
System.Reflection.PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
foreach (System.Reflection.PropertyInfo pi in propertys)
{
tempName = pi.Name;
if (dt.Columns.Contains(tempName))
{
if (!pi.CanWrite) continue;
object value = dr[tempName];
if (pi.PropertyType.FullName == "System.Int32")//此处判断下Int32类型,如果是则强转
value = Convert.ToInt32(value);
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐