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.
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.
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.
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.
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.
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With