Search code examples
c#entity-framework-coredbset

Dynamic DbSet in Entity Framework Core


string tableName = "TblStudents";
Dictionary<string, Type> myDictionary = new Dictionary<string, Type>()
{
    { "TblStudents", typeof(TblStudent) },
    { "TblTeachers", typeof(TblTeacher) }
};

// Context always same
DBContext dbContext = new DBContext();
DbSet dbSet = dbContext.Set(myDictionary[tableName]);

Above code is from this post where I can DbSet dynamically. How can I make this work in Entity Framework Core?

I get an error at

DbSet dbSet = dbContext.Set(myDictionary[tableName]);

seems like Set method has been changed in the new version.

Help is appreciated.


Solution

  • If you're trying to get the DbSet<TEntity> by TEntity, use:

    var dbSet = dbContext.Set<TEntity>();
    

    If you want to call that method based off a string name and your dictionary, you'll have to use reflection.

    EF Core does not appear to have a non-generic DbSet so you'll have to use one of the non-generic interfaces such as IQueryable and I'd include a Func that you can invoke to get the IQueryable instead of just the type if you insist on going the dictionary mapping route. For example:

    var myDictionary = new Dictionary<string, Func<DbContext, IQueryable>>()
    {
        { "TblStudents", ( DbContext context ) => context.Set<TblStudent>() }
    };
    
    var dbSet = myDictionary[ "TblStudents" ].Invoke( dbContext );