【转】dataset和实体类 之间的转换1
本文来自:http://blog.csdn.net/zj1103/article/details/3416016
//dataset转实体类
public static IList<T> FillModel(DataSet ds)
{
List<T> l = new List<T>();
T model = default(T);
if (ds.Tables[0].Columns[0].ColumnName == "rowId")
{
ds.Tables[0].Columns.Remove("rowId");
}
foreach (DataRow dr in ds.Tables[0].Rows)
{
model = Activator.CreateInstance<T>();
foreach (DataColumn dc in dr.Table.Columns)
{
PropertyInfo pi = model.GetType().GetProperty(dc.ColumnName);
if (dr[dc.ColumnName] != DBNull.Value)
pi.SetValue(model, dr[dc.ColumnName], null);
else
pi.SetValue(model, null, null);
}
l.Add(model);
}
return l;
}
/// <summary>
/// 将实体类转换成DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="i_objlist"></param>
/// <returns></returns>
public static DataTable Fill<T>(IList<T> objlist)
{
if (objlist == null || objlist.Count <= 0)
{
return null;
}
DataTable dt = new DataTable(typeof(T).Name);
DataColumn column;
DataRow row;
System.Reflection.PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (T t in objlist)
{
if (t == null)
{
continue;
}
row = dt.NewRow();
for (int i = 0, j = myPropertyInfo.Length; i < j; i++)
{
System.Reflection.PropertyInfo pi = myPropertyInfo[i];
string name = pi.Name;
if (dt.Columns[name] == null)
{
column = new DataColumn(name, pi.PropertyType);
dt.Columns.Add(column);
}
row[name] = pi.GetValue(t, null);
}
dt.Rows.Add(row);
}
return dt;
}