views:

48

answers:

1

Hi,

Is there a way to initialize an object from a database query that returns a datatable? What I mean is, I have an oracle stored procedure that returns a refcursor for data from a table. In my code, I have an object for that table (not using an ORM). Is there an easy way to initialize the object from the data in the datatable, or do I have to go and initialize the object and set all the properties manually?

A: 

You could use reflection in an extension method:

public static T CreateFrom<T>(this DataTable dt) where T : new()
{
    T obj = new T();
    obj.InitFrom(dt);
    return obj;
}

public static void InitFrom<T>(this T obj, DataTable dt)
{
    object currentValue;
    DataRow row = dt[0];

    foreach(var prop in typeof(T).GetProperties())
    {
     currentValue = row[prop.Name];
     prop.SetValue(obj, currentValue, null);
    }
}
Lee