如何根据表名称在DbContext中选择正确的DbSet
说我有一个带有以下DbSet的DbContext
Say I have a DbContext with the following DbSets
class Amimals : DbContext
{
public DbSet<Dog> Dogs { get; set; }
public DbSet<Cat> Cats { get; set; }
}
在每个EntityTypeConfiguration里面,我为每个DbSet定义表
Inside of each EntityTypeConfiguration I am defining the table for each DbSet like
class DogConfig : EntityTypeConfiguration
{
public DogConfig()
{
this.ToTable("DOG_TABLE");
...
}
}
现在,如果我有表名和DbContext,该如何获取和使用正确的DbSet?
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 */
...
}
}
您可以使用方法DbContext.Set(Type entityType)
通过Type
从DbContext获取DbSet.因此,如果您将模型类名称作为字符串,则应该对实际的clr类型进行一些映射.
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.
例如:
string tableName = "Cat";
var type = Assembly.GetExecutingAssembly()
.GetTypes()
.FirstOrDefault(t => t.Name == tableName);
if(type != null)
DbSet catContext = context.Set(type);
您还可以使用完整程序集合格名称Type.GetType('...')
You also can get type from string using Full Assembly Qualified Name Type.GetType(' ... ')
如果您可以某种方式以通用方式存储配置并使用通用context.Set<T>()
方法,将会更加容易.
If will be even easier if you can store configurations somehow in generic way and use the generic context.Set<T>()
method.