【问题标题】:Entity Framework Code First - Configuration in another fileEntity Framework Code First - 在另一个文件中配置
【发布时间】:2011-09-19 18:14:26
【问题描述】:

使用 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#。

【问题讨论】:

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


    【解决方案1】:

    您需要创建一个继承自 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 更详细地介绍了使用配置类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-15
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多