Conversion between dataset and object classes
// Convert dataset to object class
Code
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;
}
Convert an object class to a able
Code
/// <Summary>
/// Convert an object class to a able
/// </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;
}