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

posted on 2009-08-04 10:18  新郎  阅读(3863)  评论(0编辑  收藏  举报