实体框架核心配置 [英] Entity Framework core configurations
问题描述
在EF 6中,我们可以直接将EntityTypeConfiguration传递给模型构建器以构建映射,并使我们的配置类与上下文分离,而不必在代码中过于冗长.
In EF 6 we could directly pass EntityTypeConfiguration to model builder to build maps and keep our configuration class separate from context without being too verbose in code.
他们是否已删除EF core中的那些地图.有没有一种方法可以在每个类的模型构建器中添加配置而无需添加配置?
Have they removed those maps in EF core. Is there a way to add configuration without doing it in model builder for every class?
推荐答案
最好的方法是使配置代码远离OnModelCreating
方法.因此,您可以执行以下操作:
The best way is to keep the configuration code away from the OnModelCreating
method. So you can do something like:
创建一个用于存储实际配置的类:
Create a class where you will store the actual configuration:
public class ApplicationUserConfiguration
{
public ApplicationUserConfiguration(EntityTypeBuilder<ApplicationUser> entity)
{
// Here you have all the good stuff
entity.ToTable("user", "identity");
entity.Property(p => p.Id)
.HasColumnName("id);
// And so on ....
}
}
并在您的OnModelCreating
中实例化新创建的类并传递正确的实体:
And into your OnModelCreating
instantiate the new created class and pass the correct entity:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Your custom configs here
new ApplicationUserConfiguration(builder.Entity<ApplicationUser>());
}
这是达到目标的简单且简单的方法.
Is clean and a simple way to achieve the goal.
这篇关于实体框架核心配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!