Dynamic DbSet in Entity Framework Core

c# dbset entity-framework-core

Question

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.

1
2
10/4/2018 4:13:28 AM

Popular Answer

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 );
1
10/4/2018 3:55:55 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow