将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;
            }
        }
原文地址:https://www.cnblogs.com/cang12138/p/7199568.html