DataTable転送リスト<br>汎用クラス

2998 ワード

/// <summary>

/// DataTable List<Model> 【 】

/// </summary>

public class ModelConvertHelper<T> where T : new()

{

public static IList<T> ConvertToModel(DataTable dt)

{

//  

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))

{

//  Set

if (!pi.CanWrite) continue;



object value = dr[tempName];

if (value != DBNull.Value)

pi.SetValue(t, value, null);

}

}

ts.Add(t);

}

return ts;

}

}

//DataTableをIList IList vlistTable = ModelConvertHelper.ConvertToModel(dtTable);