0

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?

Nick
  • 1,417
  • 1
  • 14
  • 21
  • You might want to look at http://stackoverflow.com/questions/545328/datatable-to-generic-list-memory-leak/545429#545429 and http://stackoverflow.com/questions/564366/generic-list-to-datatable/564373#564373 – Marc Gravell Sep 17 '09 at 21:07

1 Answers1

0

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
  • 142,018
  • 20
  • 234
  • 287