使用 Fluent API 分离表到实体的映射的最佳方法是什么,以便它全部在一个单独的类中,而不是内联在 OnModelCreating 方法中?
我目前在做什么:
public class FooContext : DbContext {
// ...
protected override OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Entity<Foo>().Property( ... );
// ...
}
}
我想要什么:
public class FooContext : DbContext {
// ...
protected override OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.LoadConfiguration(SomeConfigurationBootstrapperClass);
}
}
你是怎么做到的?我正在使用 C#。
最佳答案
您将要创建一个继承自 EntityTypeConfiguration 的类类,像这样:
public class FooConfiguration : EntityTypeConfiguration<Foo>
{
public FooConfiguration()
{
// Configuration goes here...
}
}
然后你可以像这样加载配置类作为上下文的一部分:
public class FooContext : DbContext
{
protected override OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new FooConfiguration());
}
}
This article更详细地介绍了如何使用配置类。
关于c# - Entity Framework Code First - 在另一个文件中配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7475403/