Say I have a DbContext with the following DbSets
class Amimals : DbContext
{
public DbSet<Dog> Dogs { get; set; }
public DbSet<Cat> Cats { get; set; }
}
Inside of each EntityTypeConfiguration I am defining the table for each DbSet like
class DogConfig : EntityTypeConfiguration
{
public DogConfig()
{
this.ToTable("DOG_TABLE");
...
}
}
Now, if I have the table name and the DbContext, how can I grab and use the correct DbSet?
void foo()
{
string tableName = this.GetTableName();
using(Animals context = new Animals())
{
/* Made up solution */
DbSet animalContext = context.Where(c => c.TableName == tableName);
...
/* Do something with 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. So it makes perfect sense that you will get a combination of both!
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.
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.
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.
You can get DbSet from DbContext by Type
using the method DbContext.Set(Type entityType)
. So if you have the model class name as string you should do some mapping to actual clr type.
For example:
string tableName = "Cat";
var type = Assembly.GetExecutingAssembly()
.GetTypes()
.FirstOrDefault(t => t.Name == tableName);
DbSet catContent;
if(type != null)
catContext = context.Set(type);
You also can get type from string using Full Assembly Qualified Name Type.GetType(' ... ')
If will be even easier if you can store configurations somehow in generic way and use the generic context.Set<T>()
method.
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