將DataTable轉換為List 對象遇到問題:類型“System.Int64”的對象無法轉換為類型“System.Int32”。


可以利用反射將DataTable轉換為List<T>對象:原始鏈接http://www.jb51.net/article/67386.htm

但是該方法在DataTable里某個字段類型是Int32會有問題,報異常:類型“System.Int64”的對象無法轉換為類型“System.Int32”。

可在賦值的時候加一句:

if(pi.GetMethod.ReturnParameter.ParameterType.Name == "Int32")
{
value = Convert.ToInt32(value);
}
pi.SetValue(t, value, null);

整體代碼:

 1 /// <summary> 
 2 /// 利用反射將DataTable轉換為List<T>對象
 3 /// </summary> 
 4 /// <param name="dt">DataTable 對象</param> 
 5 /// <returns>List<T>集合</returns> 
 6 public static List<T> DataTableToList<T>(DataTable dt) where T : class, new()
 7 {
 8 // 定義集合 
 9 List<T> ts = new List<T>();
10 //定義一個臨時變量 
11 string tempName = string.Empty;
12 //遍歷DataTable中所有的數據行 
13 foreach (DataRow dr in dt.Rows)
14 {
15 T t = new T();
16 // 獲得此模型的公共屬性 
17 PropertyInfo[] propertys = t.GetType().GetProperties();
18 //遍歷該對象的所有屬性 
19 foreach (PropertyInfo pi in propertys)
20 {
21 tempName = pi.Name;//將屬性名稱賦值給臨時變量 
22 //檢查DataTable是否包含此列(列名==對象的屬性名) 
23 if (dt.Columns.Contains(tempName))
24 {
25 //取值 
26 object value = dr[tempName];
27 //如果非空,則賦給對象的屬性 
28 if (value != DBNull.Value)
29 {
30 if (pi.GetMethod.ReturnParameter.ParameterType.Name == "Int32")
31 {
32 value = Convert.ToInt32(value);
33 }
34 pi.SetValue(t, value, null);
35 }
36 }
37 }
38 //對象添加到泛型集合中 
39 ts.Add(t);
40 }
41 return ts;
42 }

 

其他類型轉換匯總

 1 public static  List<T> ToList<T>(this DataTable dt) where T:class,new()
 2 {
 3 Type t=typeof(T);
 4 PropertyInfo[] propertys = t.GetProperties();
 5 List<T> lst = new List<T>();
 6 string typeName = string.Empty;
 7 foreach (DataRow dr in dt.Rows)
 8 {
 9 T entity = new T();
10 foreach (PropertyInfo pi in propertys)
11 {
12 typeName = pi.Name;
13 if (dt.Columns.Contains(typeName))
14 {
15 if (!pi.CanWrite) continue;
16 object value = dr[typeName];
17 if (value == DBNull.Value) continue;
18 if (pi.PropertyType == typeof(string))
19 {
20 pi.SetValue(entity,value.ToString(),null);
21 }
22 else if (pi.PropertyType == typeof(int) || pi.PropertyType == typeof(int?))
23 {
24 pi.SetValue(entity,int.Parse(value.ToString()), null);
25 }
26 else if (pi.PropertyType == typeof(DateTime?) || pi.PropertyType == typeof(DateTime))
27 {
28 pi.SetValue(entity, DateTime.Parse(value.ToString()), null);
29 }
30 else if (pi.PropertyType == typeof(float))
31 {
32 pi.SetValue(entity, float.Parse(value.ToString()), null);
33 }
34 else if (pi.PropertyType == typeof(double))
35 {
36 pi.SetValue(entity, double.Parse(value.ToString()), null);
37 }
38 else
39 {
40 pi.SetValue(entity,value, null);
41 }
42 }
43 }
44 lst.Add(entity);
45 }
46 return lst;
47 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM