gpt4 book ai didi

c# - EF Core 中的 modelBuilder.Configurations.AddFromAssembly

转载 作者:太空狗 更新时间:2023-10-29 21:42:50 29 4
gpt4 key购买 nike

EntityFramework 6.x 中,如果我们有很多 EntityConfiguration 类,那么我们可以在 OnModelCreating(ModelBuilder modelBuilder) 中分配所有这些类如下而不是一一:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

modelBuilder.Configurations.AddFromAssembly(typeof(MyDbContext).Assembly);
}

是否有类似 modelBuilder.Configurations.AddFromAssembly Entity Framework Core 的东西。

最佳答案

对于 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 核心 >= 2.2

从 EF Core 2.2 开始,您无需编写任何自定义扩展方法。为此,EF Core 2.2 添加了 ApplyConfigurationsFromAssembly 扩展方法。您可以按如下方式使用它:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

modelBuilder.ApplyConfigurationsFromAssembly(typeof(UserConfiguration).Assembly); // Here UseConfiguration is any IEntityTypeConfiguration
}

谢谢。

关于c# - EF Core 中的 modelBuilder.Configurations.AddFromAssembly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51842709/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com