将DataTable转换为List<T>对象遇到问题:类型“System.Int64”的对象无法转换为类型“System.Int32”。
2017-07-18 11:29
721 查看
报错信息:
将DataTable转换为List<T>对象遇到问题,类型“System.Int64”的对象无法转换为类型“System.Int32”。
解决方案:
以下红色为新添加的,单独判断下Int32,然后强转一次
将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; } }
相关文章推荐
- 将DataTable转换为List<T>对象遇到问题:类型“System.Int64”的对象无法转换为类型“System.Int32”
- MVC 无法将类型“System.Collections.Generic.List<AnonymousType#1>”隐式转换为“System.Collections.Generic.IList<Mvc3Modeltest.Models.Movie>”。存在一个显式转换(是否缺少强制转换?))
- 无法将类型“System.Collections.Generic.IEnumerable<EmailSystem.Model.TemplateInfo>”隐式转换为“System.Collections.Generic.List<EmailSystem.Model.TemplateInf
- 无法将类型“System.Collections.Generic.List<anonymous type:string ClassID,string ClsssName>”隐式转换为“System.Collections.Generic.List<Ecology.Model.EnergyFlowGraph>”
- 关于MVC中无法将类型为“System.Int32”的对象强制转换为类型“System.String”的问题。
- NHibernate无法将类型“System.Collections.Generic.IList<T>”隐式转换为“System.Collections.Generic.IList<IT>
- 再谈使用Emit把Datatable转换为对象集合(List<T>)
- 並行迭代DataTable,无法从DataRowCollection转换为IEnumerable<System.Data.DataRowCollection>
- Linq集合查询出现无法将类型为“System.Int32”的对象强制转换为类型“System.String”异常
- Struts2中表达式集合对象List<T>与对象<T>的取值时遇到的变量名的问题
- 工作总结 无法确定条件表达式的类型,因为“<null>”和“System.DateTime”之间没有隐式转换 解决办法 object——Nullable<T> (可空类型)
- 关于IList类型与IList<T>在运行时类型转换失败的问题
- EF实体查询出的数据List<T>转DataTable出现【DataSet 不支持 System.Nullable<>】的问题
- 解决GridView绑定时无法将类型为 <>f__AnonymousType0`2[xx] 的对象强制转换为类型“xxx”的方法
- C# Winform DataGrid 绑定List<> Or ObservableCollection<> 类型无法自动刷新问题
- C# 类型“System.String”的对象无法转换为类型“System.Int32”
- 属性的字符串表示形式“<%=Value %>"创建“System.Int32”类型的对象。
- 无法确定条件表达式的类型,因为“<null>”和“System.DateTime”之间没有隐式转换 解决办法
- 具有键“XXX”的 ViewData 项属于类型“System.Int32”,但它必须属于类型“IEnumerable<SelectListItem>
- ASP.NET.MVC异常--无法将类型为System.Int32的对象强制转换为类型System.String