dimanche 2 mai 2021

Entity Framework, generics: how to work with multiple tables that derive from a common inherited type?

Suppose I have a DbSet like so:

DbSet<Teacher>

And a Teacher inherits from a Person (not part of the EF generated classes).

public partial class Teacher: Person
{
}

And I have a list of DbSets like so

var tableList = new List<Type>() { typeof(DbSet<Teacher>), typeof(DbSet<Student>), ... };

Then I want to create a generic function that does the same thing for each of the tables in the list.

How do I do something like the following if I know that all the tables in the list can inherit from the same Person type:

foreach(var tableType in tableList)
{
    var table = (DbSet<Person>)Activator.CreateInstance(tableType);

    var existing = table.Where(x => x.Name == "whatever");

    if (!existing.Any())
    {
         table.Add(new Person{ Name = "Whatever" });
    }
...

The problem is that EF doesn't know which table in the database I want to talk to. How do I tell it that 'in this loop I want you to save the new person to the Student table, in this loop I want you to save to the Teacher table, etc?

I've tried initialising the table like so but neither are useful:

var table = (DbSet<dynamic>)Activator.CreateInstance(tableType);

var table = (DbSet<tableType>)Activator.CreateInstance(tableType);

Note: I know I could've made loads of separate very similar functions for each table type but I've made the above example simple to make the problem easier to understand, I'm not actually saving different types of people in a loop based on whether their name exists. Any ideas? Thanks!





Aucun commentaire:

Enregistrer un commentaire