1 回答
TA贡献1900条经验 获得超5个赞
对于 EF 核心 <= 2.1
你可以写一个扩展方法如下:
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);
}
}
}
然后在OnModelCreating如下:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyAllConfigurations();
}
对于 EF Core >= 2.2
从 EF Core 2.2 开始,您无需编写任何自定义扩展方法。EF Core 2.2ApplyConfigurationsFromAssembly为此添加了扩展方法。您可以按如下方式使用它:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(typeof(UserConfiguration).Assembly); // Here UseConfiguration is any IEntityTypeConfiguration
}
谢谢你。
- 1 回答
- 0 关注
- 584 浏览
添加回答
举报