C# DataTable转实体+實例

一、datatable轉實體代碼


 /// <summary>

        /// DataTable转实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public List<T> DataTableConvertEntity<T>(DataTable dt) where T : class, new()
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return null;
            }
            List<T> List = new List<T>();
            foreach (DataRow dr in dt.Rows)
            {
                T model = new T();
                for (int i = 0; i < dr.Table.Columns.Count; i++)
                {
                    PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
                    if (propertyInfo != null && dr[i] != DBNull.Value)
                        propertyInfo.SetValue(model, dr[i], null);
                }

                List.Add(model);
            }
            return List;
        }


 

 /// <summary>

        /// DataTable转实体+判斷空值---此方法可以GET到欄位名和值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>

public static List<T> ConvertToModel<T>(DataTable dt) where T : new()

{
// 定义集合
List<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) continue;
if (pi.PropertyType == typeof(string))
{
pi.SetValue(t, value.ToString(), null);
}
else
{
pi.SetValue(t, value, null);
}
}
}
ts.Add(t);
}
return ts;
}

 

public static List<T> ToList<T>(this DataTable dt) where T : class, new()
{

var list =ConvertToModel<T>(dt);
return list;
}


 

 

二、使用案例

public List<MSDS> GetChemicalNameAndChemicalArea(string MappingType, string adminEmpno)
{
DataTable dt = new DataTable();
#region 取得mapping表 站點信息
Msds_Mapping value = new Msds_Mapping()
{
mapping_type = MappingType,
value1 = "0",
value2 = "0",
value3 = "0",
value4 = "0",
value5 = "0"
};
dt = _msdsDB.Mapping(adminEmpno, "admin", value);//取得mapping表
//List<Msds_Mapping> list = DataTableConvertEntity<Msds_Mapping>(dt);//DataTable转实体

List<Msds_Mapping> list = dt.ToList<Msds_Mapping>();

List<MSDS> list1 = new List<MSDS>();
foreach (var item in list)
{
MSDS MSDS = new MSDS()
{
label=item.value1,
value=item.value2
};
list1.Add(MSDS);
}
#endregion
return list1;
}

posted @ 2020-08-07 16:49  A大洋芋  阅读(184)  评论(0编辑  收藏  举报