Friday, July 27, 2012

Map SqlReader to Bussiness Entity Collection using Reflection C#

Reflection provides objects (of type Type) that encapsulate assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, Reflection enables you to access them. For more information

Map Data To Business Entity Collection

MapDataToBusinessEntityCollection is a generic Reflective method. We pass in the data-type for the objects to be mapped as a generic parameter along with a data reader. We use reflection to find the properties in this type and we use the meta data in the DataReader to find the fields.

Whenever we find a field from the data reader that has a matching writable property in the generic type, we pull the value from the DataReader and assign it to a newly created object. Regardless of how many properties are in T, this method will map every property that has a matching field in the DataReader. Any properties that are not in the DataReader will be unmapped. Any fields in the data reader that do not have a matching property will be ignored. The validation logic is handled in the implementation of the properties in T.

public static List<T> MapDataToBusinessEntityCollection<T>(IDataReader dr) 
where T : new()
 {
  Type businessEntityType = typeof (T);
  List<T> entitys = new List<T>();
  Hashtable hashtable = new Hashtable();
  PropertyInfo[] properties = businessEntityType.GetProperties();
  foreach (PropertyInfo info in properties)
  {
      hashtable[info.Name.ToUpper()] = info;
  }
  while (dr.Read())
  {
      T newObject = new T();
      for (int index = 0; index < dr.FieldCount; index++)
      {
          PropertyInfo info = (PropertyInfo)
                              hashtable[dr.GetName(index).ToUpper()];
          if ((info != null) && info.CanWrite)
          {
              info.SetValue(newObject, dr.GetValue(index), null);
          }
      }
      entitys.Add(newObject);
  }
  dr.Close();
  return entitys;
}
 

No comments:

Post a Comment