Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select correct DbSet in DbContext based on table name

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 */
        ...
    }
}
like image 696
DobleA Avatar asked Oct 10 '14 18:10

DobleA


People also ask

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. So it makes perfect sense that you will get a combination of both!

What is DbSet <>?

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.

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 does DbSet Tentity class represent in Entity Framework?

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

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.

like image 132
Viktor Bahtev Avatar answered Oct 07 '22 02:10

Viktor Bahtev