导航

dataset和实体类 之间的转换

Posted on 2011-03-15 22:40  毅无涯  阅读(247)  评论(0编辑  收藏  举报

//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;
}