Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 */
        ...
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
702 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

if(type != null)
    DbSet 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...