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

c# entity-framework linq reflection

Question

Let's say I have the following DbSets in my DbContext.

class Amimals : DbContext
{
    public DbSet<Dog> Dogs { get; set; }
    public DbSet<Cat> Cats { get; set; }
}

I define the table for each DbSet inside of each EntityTypeConfiguration.

class DogConfig : EntityTypeConfiguration
{
    public  DogConfig()
    {
        this.ToTable("DOG_TABLE");
        ...
    }
}

How can I find and utilize the right DbSet if I know the table name and the DbContext?

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 */
        ...
    }
}
1
9
10/10/2014 6:24:18 PM

Accepted Answer

DbSet can be obtained by using DbContext toType utilizing the techniqueDbContext.Set(Type entityType) . Therefore, you should perform some mapping to the actual clr type if you have the model class name as a string.

For instance:

string tableName = "Cat";
var type = Assembly.GetExecutingAssembly()
        .GetTypes()
        .FirstOrDefault(t => t.Name == tableName);

if(type != null)
    DbSet catContext = context.Set(type);

Using Full Assembly Qualified Name Type, you may also determine the type from a string. GetType(' ', '...)

If you can save configurations in some manner that is generic and use the genericcontext.Set<T>() method.

18
10/10/2014 6:48:42 PM

Popular Answer

The following strategy also works well for me:

Type t = Type.GetType(Assembly.GetExecutingAssembly().GetName().Name + "." + "TableName");
DbSet dbset = dbcontext.Set(t);


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