Click here to Skip to main content
Click here to Skip to main content

Object Relational Mapping via Reflection

By , 14 Jun 2011
 
Before I learned about reflection, performing object-relational mapping was a painful and slow task.
 
You would design your Data-Object with attributes similar to the database table it would accept data from, then there would be the long and painful process of initializing the object from the data row.
 
This would lead to lots of code that looked like this:
 
// load customer details from row:
this.customerid = (int)customerRow["customerid"];
this.namefirst  = (string)customerRow["namefirst"];
this.namelast   = (string)customerRow["namelast"];
 
Which is just painful.
 
But, with one simple extension method, this code could be replaced by:
 
this.SetPropertiesFrom(customerRow);
 
Regardless of the number of fields, for any object...
 
How does it work?
 
Reflection allows you to examine any object's properties, methods, fields etc at run-time.
 
the SetPropertiesFrom method simply enumerates the object's public properties, and sets the value for each one that has a matching column in the data-row.
 
The only restriction is that the pubic properties of the object being populated must match the column names of the table. However this could be overcome by adding custom attribute decorations to the properties to indicate the source field, but that is a topic for a full article.
 
Here is the method in full, as an extension method for Object. Anywhere this class is in scope, each object will gain the SetPropertiesFrom method.
 
/// <summary>
/// extension methods that allow dynamic population of data objects through reflection
/// </summary>
public static class DynamicDataExtensions
{
    /// <summary>
    /// populate the public properties of this object from a data-row;
    /// </summary>
    /// <param name="obj"></param>
    /// <param name="row"></param>
    public static void SetPropertiesFrom(this Object obj, DataRow row)
    {
        // enumerate the public properties of the object:
        foreach (PropertyInfo property in obj.GetType().GetProperties())
        {
            // does the property name appear as a column in the table?
            if (row.Table.Columns.Contains(property.Name))
            {
                // get the data-column:
                DataColumn column = row.Table.Columns[property.Name];
 
                // get the value of the column from the row:
                object value = row[column];
 
                // set the value on the property:
                if (!(value is DBNull))
                    property.SetValue(obj, Convert.ChangeType(value, property.PropertyType), null);
 
            }
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Simon Bridge
Technical Lead Evolution Management Consulting
Australia Australia
Member
Wrote his first computer game in Microsoft Basic, on a Dragon 32 at age 7. It wasn't very good.
Has been working as a consultant and developer for the last 15 years,
Discovered C# a few years ago and hasn't looked back.
Feels wierd talking about himself in the third person.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Generalentity framework?memberjohannesnestler26 Jun '11 - 10:06 
GeneralReason for my vote of 3 Such reflection is much slower then ...memberKelqualyn23 Jun '11 - 8:44 
Reason for my vote of 3
Such reflection is much slower then handwritten code. Reflective code can be rewritten to be as fast as handwritten one.
GeneralRe: I am very interested in how you would re-write this to be a...memberSimon Bridge14 Jul '11 - 19:52 
GeneralReason for my vote of 5 This is going to come in very useful...memberMember 780287320 Jun '11 - 21:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 14 Jun 2011
Article Copyright 2011 by Simon Bridge
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid