c# - Entity Framework Code First - 在另一个文件中配置

标签 c# configuration entity-framework-4.1 code-first

使用 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/

相关文章:

asp.net-mvc - 使用 Entity Framework 保存更改/更新数据集中的现有对象,而不必分别设置每个属性

c# - WPF mvvm 绑定(bind),获取/设置值 : issue with preventing update value

c# - 如何在 ashx webHandler ASP.NET 3.5 中读取 postdata

c# - PayPal 定期捐款分期付款

c# - 如何在 C# 中使用 StreamReader(新手)

asp.net - 为什么我想将 UnitOfWork 与存储库模式一起使用?

session - 我正在尝试将 PassportJs 与多种类型的用户一起使用(每种用户都有不同的模型)。我究竟做错了什么?

java - spring boot 配置属性错误

windows - Solr:在 Windows 中更改数据目录

database - Entity Framework 4.1 - 交换数据库