Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 686
bbusdriver Avatar asked Oct 04 '18 01:10

bbusdriver


People also ask

What is DbSet in Entity Framework Core?

In Entity Framework Core, the DbSet represents the set of entities. In a database, a group of similar entities is called an Entity Set. The DbSet enables the user to perform various operations like add, remove, update, etc. on the entity set.

What is the difference between DbContext and DbSet?

Intuitively, a DbContext corresponds to your database (or a collection of tables and views in your database) whereas a DbSet corresponds to a table or view in your database.

What is the use of DbSet in Entity Framework?

A DbSet represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext.

Is DbSet part of DbContext?

The DbSet class represents an entity set that can be used for create, read, update, and delete operations. The context class (derived from DbContext ) must include the DbSet type properties for the entities which map to database tables and views.


1 Answers

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 );
like image 105
Moho Avatar answered Oct 08 '22 07:10

Moho