C# Is there a way to fill in a variable for the generic T SQLiteConnection Table<T>?

126 views Asked by At

I want to loop through different tables in a SQLite database and perform the same actions. The T in Table expects a class name that matches a table name and functions as a container for the data in that table. I want to do something like this:

For each table in TableList:
  Check common data in table
  Update as needed

Here's an idea of how the code would look:

var path = //Some system path
conn = new SQLiteConnection(path);
foreach(var category in Categories)
{
    var details = (from x in this.conn.Table<category>() select x)
    //Do stuff with data
}

The above gives the error "category is a variable but is used like a type." I've tried converting the category to a generic type like so:

var path = //Some system path
conn = new SQLiteConnection(path);
foreach(var category in Categories)
{
                string name = category.ToString();
                Type targetType = Type.GetType(name);

                //DatabaseContainer is the type all the categories inherit from
                Type genericType = typeof(DatabaseContainer).MakeGenericType(targetType);
                object instance = Activator.CreateInstance(genericType);
                var details = (from x in this.conn.Table<instance>() select x)
}

targetType, genericType, and instance all give the same error "category is a variable but is used like a type." I cannot change the structure of the database in any way. I'm not sure if this is possible, or if I have to write the same code for each table.

0

There are 0 answers