[英]Apply all IEntityTypeConfiguration derived classes in EF Core
Does anyone know of a way or have an implementation to apply ALL classes that derive from IEntityTypeConfiguration<>
to the DbContext
at runtime? 有没有人知道一种方法或有一个实现在运行时将所有从
IEntityTypeConfiguration<>
派生的类应用到DbContext
?
There doesn't seem to be anything built in and loading each one manually via: 似乎没有内置任何东西并通过以下方式手动加载每个:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new Table1Config())
modelBuilder.ApplyConfiguration(new Table2Config())
...
modelBuilder.ApplyConfiguration(new TableNConfig())
}
is going to prove rather tedious for a database with many tables. 对于具有许多表的数据库来说,这将变得相当繁琐。
You can write an extension method as follows: 您可以编写扩展方法,如下所示:
public static class ModelBuilderExtensions
{
public static void ApplyAllConfigurations(this ModelBuilder modelBuilder)
{
var typesToRegister = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.GetInterfaces()
.Any(gi => gi.IsGenericType && gi.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>))).ToList();
foreach (var type in typesToRegister)
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.ApplyConfiguration(configurationInstance);
}
}
}
Then in the OnModelCreating
as follows: 然后在
OnModelCreating
中如下:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyAllConfigurations();
}
From EF Core 2.2
you don't need to write any custom extension method. 从
EF Core 2.2
您不需要编写任何自定义扩展方法。 EF Core 2.2
added ApplyConfigurationsFromAssembly
extension method for this purpose. ApplyConfigurationsFromAssembly
EF Core 2.2
添加了ApplyConfigurationsFromAssembly
扩展方法。 You can just use it as follows: 您可以按如下方式使用它:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(typeof(UserConfiguration).Assembly); // Here UseConfiguration is any IEntityTypeConfiguration
}
Thank you. 谢谢。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var implementedConfigTypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => !t.IsAbstract
&& !t.IsGenericTypeDefinition
&& t.GetTypeInfo().ImplementedInterfaces.Any(i =>
i.GetTypeInfo().IsGenericType && i.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>)));
foreach (var configType in implementedConfigTypes)
{
dynamic config = Activator.CreateInstance(configType);
modelBuilder.ApplyConfiguration(config);
}
}
This is now built in to EF Core 2.2: 现在内置于EF Core 2.2中:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(typeof(PersonConfiguration).Assembly);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.