mercredi 26 août 2015

Best way to populate datatable into datamodel with huge number of properties in C#

I have a mainframe database from which I am exporting 5 lakh records using ODBC . Now I have to populate the datatable into data model(object). The data model or class has more than 150 properties which needs to be populated from datatable. I am using reflection to do so inside every iteration of each datarow. I could have use list or reader properties to populate from datatable but there I have to define 150 members. To avoid and make it more generic I choosed to use reflection.

 DataModel model = null;
//DataModel  is a class containing various properties 
//i.e public class DataModel
//{
//  public string Name {get;set;}
 // public string Role {get;set;}
//etc....150 properties
//}

    dt = new DataTable();
    using(OdbcDataReader reader = cmd.ExecuteReader())
    {
    DatatTable dtSchema = reader.GetSchemaTable();
    List<DataColumn> listCols = new List<DataColumn>();
    if(dtSchema != null)
    {
     foreach(DataRow drow in dtSchema.Rows)
    {
    string ColName = Convert.ToString(drow["ColumnName"]);
    DataColumn column = new DataColumn(columnName,(Type)(drow["DataType"]));
    listCols.Add(column);
    dt.Columns.Add(column);
    }
    PropertyInfo[] properties = typeof(DataModel).GetProperties();

    while(reader.Read())
    {
    DataRow dataRow = dt.NewRow();
    for(int i = 0; i < listCols.COunt; i++)
    {

    dataRow[((DataCOlumn)listCols[i])]
    }
    dt.Rows.Add(dataRow);

    model = new DataModel();
    foreach(PropertyInfo property in properties)
    {
      if(dt.Columns.Contains(property.Name))
        SetValue(model,property.name,dataRow[property,name]);

    }
    if(model != null) lst.Add(model);
    }

    }

I am getting exception by using this approach of reflection . Can the above be rectified and any different approach can be used ? I am using reflection to do so inside every iteration of each datarow. Please tell me is there any other good or more performance efficient method apart from reflection to do so. (Please note I have more than 150 properties that needs to be populated)





Aucun commentaire:

Enregistrer un commentaire