0

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.

Nicholas
  • 23
  • 4
  • You could do it with reflection, but it's unclear what you would do with the result if you don't know its type. You've just written `var details = ...` and not done anything with it, what are you actually trying to do? – Charlieface Jun 10 '21 at 19:19
  • The select statement will have a where clause using a key common to each of the records. The result would be IEnumerable, and it would be used to find and change certain records from each table depending on result. – Nicholas Jun 10 '21 at 21:00
  • Perhaps you should create an interface for that one column which each type would implement, then you can make a generic method constrained `where T : IYourInterface` (don't be tempted to use the interface directly, SQLite.NET won't understand it) – Charlieface Jun 10 '21 at 21:36

0 Answers0