vendredi 28 juillet 2017

Dynamically populate generic list of objects without concrete data type

I have a database with around 100 or so table. What I am trying to do is the following:

  1. Get a list of tables in the database.
  2. Loop through each table in the list, and select all records in the table into a Data Table.
  3. For each Data Table, dynamically generate a Generic List of POCO classes
  4. Read each Data Row and populate the object, then add it to the list.

I am getting through items 1 and 2 fine. But for items 3 and 4 I am having trouble. Here is the code I have:

Type type = Type.GetType(tableName);
var list = Utility.BindList<type>(dataTable);

The exception I get is: "'type' is a variable but is used like a type."

And thinking about it, it makes sense. Of course, if I enter the actual class instead of type it works fine:

Type type = Type.GetType(tableName);
var list = Utility.BindList<Person>(dataTable);

But I don't want to have to hard code any actual classes. By the way, here is the signature of the BindList method I am calling above (this part is working fine):

public static List<T> BindList<T>(DataTable dt)
{
    // Turn Data Table into Generic List

    return list
}

Does anyone have any suggestions on how to do this?

Thanks!





Aucun commentaire:

Enregistrer un commentaire