123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using System.Data;
- using System.Reflection;
- using System.Collections;
- namespace Common.Model
- {
- /// <summary>
- /// 实体转换辅助类
- /// </summary>
- public class ModelConvertHelper<T> where T : new()
- {
- public static IList<T> ConvertToModel(DataTable dt,bool IsDateTimeEmpty = false)
- {
- // 定义集合
- IList<T> ts = new List<T>();
- // 获得此模型的类型
- Type type = typeof(T);
- string tempName = "";
- foreach (DataRow dr in dt.Rows)
- {
- T t = new T();
- // 获得此模型的公共属性
- PropertyInfo[] propertys = t.GetType().GetProperties();
- foreach (PropertyInfo pi in propertys)
- {
- tempName = pi.Name; // 检查DataTable是否包含此列
- if (dt.Columns.Contains(tempName))
- {
- // 判断此属性是否有Setter
- if (!pi.CanWrite) continue;
- object value = dr[tempName];
- if (value != DBNull.Value)
- {
- //加一重if判断,如果属性值是int32类型的,就进行一次强制转换
- if (pi.GetMethod.ReturnParameter.ParameterType.Name == "Int32")
- {
- value = Convert.ToInt32(value);
- }
- pi.SetValue(t, value, null);
- }
- if (IsDateTimeEmpty)
- {
- if (pi.PropertyType.ToString() == "System.DateTime")
- {
- if (value.ToString() == DateTime.MinValue.ToString())
- {
- pi.SetValue(t, value, null);
- }
- }
- }
- }
- }
- ts.Add(t);
- }
- return ts;
- }
- /// <summary>
- /// list转datatable
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="collection"></param>
- /// <returns></returns>
- public DataTable ListToDt<T>(IEnumerable<T> collection)
- {
- var props = typeof(T).GetProperties();
- var dt = new DataTable();
- dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
- if (collection.Count() > 0)
- {
- for (int i = 0; i < collection.Count(); i++)
- {
- ArrayList tempList = new ArrayList();
- foreach (PropertyInfo pi in props)
- {
- object obj = pi.GetValue(collection.ElementAt(i), null);
- tempList.Add(obj);
- }
- object[] array = tempList.ToArray();
- dt.LoadDataRow(array, true);
- }
- }
- return dt;
- }
- }
- }
|