Wednesday, February 15, 2006

Are you tired of writing code similar to this?

 

Customer cust = new Customer();

 

cust.CustomerID = reader.GetInt32(“CustomerID”);

cust.LastName = reader.GetString(“LastName”);

cust.FirstName = reader.GetString(“FirstName”);

 

If the answer is yes, then here is a quick solution.

 

A while back I wrote a small algorithm that uses a bit of reflection that basically handles the mapping fields in the database to the entity’s (Business Objects) properties.

 

The end result will looks something like this:

 

SqlDataReader reader = command.ExecuteReader();

 

//Return List -- Could easily be modified for scalar queries

List<Contact> contactList = new List<Contact>();

while (reader.Read())

{

    Contact contact = new Contact();

    //Map record to object

    Contact.PopulateEntity<Contact>(contact, reader);

 

    contactList.Add(contact);

}

 

While my sample uses generics, you could easily make this compatible with .NET 1.? by using “object”. The magic happens in the following method.

 

public void PopulateEntity<T>(T entity, IDataRecord record)

{

if (record != null && record.FieldCount > 0)

      {

            Type type = entity.GetType();

 

            for (int i = 0; i < record.FieldCount; i++)

            {

                  if (DBNull.Value != record[i])

                  {                      

                        PropertyInfo property = type.GetProperty(record.GetName(i));

                        if (property != null)

                        {

                              property.SetValue(entity, record[property.Name], null);

                        }

                  }

            }

      }

}

 

I have included a small example of how it could be used. (Download)

 

In the sample, I use the IDataRecord interface (http://msdn2.microsoft.com/en-us/library/93wb1heh.aspx ). This is the individual record that data readers implement.

 

Enjoy!

 

P.S. Download uses the Adventure Works sample DB Windark.Samples.zip (40.52 KB)

2/15/2006 10:33:33 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Theme design by Jelle Druyts