报错信息:

将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;
            }
        }

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-30
  • 2021-09-07
  • 2021-11-22
  • 2021-06-22
  • 2021-07-02
猜你喜欢
  • 2022-01-18
  • 2022-12-23
  • 2022-01-22
  • 2021-06-28
  • 2021-04-15
  • 2022-12-23
相关资源
相似解决方案