DataTable赋值MODEL模型
public static T ConvertToModel<T>(this DataTable DataTable, T Tmodel) { //不进行处理 if (DataTable.Rows.Count == 0) return Tmodel; //递归MODEL处理 Type t = Tmodel.GetType(); PropertyInfo[] PropertyList = t.GetProperties(); foreach (PropertyInfo Property in PropertyList) if (Property.PropertyType.ToString() == "System.String") if (DataTable.Columns.Contains(Property.Name)) Property.SetValue(Tmodel, DataTable.Rows[0][Property.Name].ToString(), null); else { } else Property.SetValue(Tmodel, ConvertToModel(DataTable, Property.GetValue(Tmodel, null)), null); return Tmodel; }
public static T ConvertToModel<T>(this DataTable DataTable, T Tmodel, Hashtable Hashtable) { //不进行处理 if (DataTable.Rows.Count == 0) return Tmodel; //递归MODEL处理 Type t = Tmodel.GetType(); PropertyInfo[] PropertyList = t.GetProperties(); foreach (PropertyInfo Property in PropertyList) if (Property.PropertyType.ToString() == "System.String") if (Hashtable.ContainsKey(Property.Name)) if (DataTable.Columns.Contains(Hashtable[Property.Name].ToString().ToUpper())) Property.SetValue(Tmodel, DataTable.Rows[0][Hashtable[Property.Name].ToString().ToUpper()].ToString(), null); else { } else { } else Property.SetValue(Tmodel, ConvertToModel(DataTable, Property.GetValue(Tmodel, null), Hashtable), null); return Tmodel; }
//使用方法 public class Model { public int ID { get; set; } public int NAME { get; set; } } DataTable dt = new DataTable(); Model Model = new Model(); dt.ConvertToModel(Model);