简体   繁体   中英

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 */
        ...
    }
}

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.

Another approach is below and work fine for me:

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

In DotNetCore I did something like this. In this case it would probably be good to use a whitelist to make sure someone doesn't ask for an undesirable entity.

    [HttpGet]
    [Route("entities/{entityName}")]
    public IActionResult GetEntities(string entityName)
    {
        var name = Assembly.GetExecutingAssembly().GetName().Name + ".path.to.your.entity." + entityName;
        Type entityType = Type.GetType(name);
        var results = _myContext
            .GetType()
            .GetMethod("Set")
            .MakeGenericMethod(entityType)
            .Invoke(_myContext, null);
        return Ok(results);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM