zoukankan      html  css  js  c++  java
  • 将DataTable转换为List<T>对象遇到问题:类型“System.Int64”的对象无法转换为类型“System.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;
                }
            }
  • 相关阅读:
    005本周总结报告
    《大道至简》读后感
    004本周总结报告
    003本周总结报告
    002本周总结报告
    001本周总结报告
    【财经】股市是不是零和博弈?
    【Spring】使用Spring的AbstractRoutingDataSource实现多数据源切换
    【Java每日一题】20170217
    【Java每日一题】20170216
  • 原文地址:https://www.cnblogs.com/cang12138/p/7199568.html
Copyright © 2011-2022 走看看