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

后端 未结 2 1992
陌清茗
陌清茗 2020-12-02 00:12

Say I have a DbContext with the following DbSets

class Amimals : DbContext
{
    public DbSet Dogs { get; set; }
    public DbSet Cats          


        
2条回答
  •  被撕碎了的回忆
    2020-12-02 00:37

    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() method.

提交回复
热议问题