简体   繁体   English

实体框架代码优先 - 在另一个文件中配置

[英]Entity Framework Code First - Configuration in another file

What is the best way to separate the mapping of tables to entities using the Fluent API so that it is all in a separate class and not inline in the OnModelCreating method? 使用Fluent API将表映射到实体的最佳方法是什么,这样它们都在一个单独的类中,而不是在OnModelCreating方法中内联?

What I am doing currently: 我目前在做什么:

public class FooContext : DbContext {
    // ...
    protected override OnModelCreating(DbModelBuilder modelBuilder) {
        modelBuilder.Entity<Foo>().Property( ... );
        // ...
    }
}

What i want: 我想要的是:

public class FooContext : DbContext {
    // ...
    protected override OnModelCreating(DbModelBuilder modelBuilder) {
        modelBuilder.LoadConfiguration(SomeConfigurationBootstrapperClass);
    }
}

How do you do this? 你怎么做到这一点? I am using C#. 我正在使用C#。

You will want to create a class that inherits from the EntityTypeConfiguration class, like so: 您将需要创建一个继承自EntityTypeConfiguration类的类,如下所示:

public class FooConfiguration : EntityTypeConfiguration<Foo>
{
    public FooConfiguration()
    {
        // Configuration goes here...
    }
}

Then you can load the configuration class as part of the context like so: 然后,您可以将配置类作为上下文的一部分加载,如下所示:

public class FooContext : DbContext
{
    protected override OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new FooConfiguration());
    }
}

This article goes into greater detail on using configuration classes. 本文将详细介绍如何使用配置类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架5代码优先配置封装 - Entity Framework 5 code-first configuration encapsulation 实体框架6首先编写代码-参照另一个现有实体添加实体 - Entity framework 6 code first - Add entity with reference to another existing entity 实体框架:多个代码优先迁移和配置种子方法 - Entity Framework: Multiple code first migrations and the configuration seed method 如何在代码优先实体框架中提供数据库配置设置? - How to provide database configuration settings in code-first Entity Framework? 实体框架代码优先处理连接字符串配置 - Entity Framework code first approach connection string configuration 实体框架代码优先:Configuration.cs种子或自定义初始化程序 - Entity Framework Code First: Configuration.cs seed or custom initializer 实体框架配置问题(EF Code-First) - Entity Framework Configuration Question (EF Code-First) 实体框架数据库优先配置 - Entity Framework Database First Configuration 如何首先在实体框架/代码中将密钥与另一个对象包装在一起 - How to wrap a key with another object in entity framework / code first 实体框架4:代码优先 - 在另一个模式中创建数据库? MapSingleType? - Entity Framework 4: Code First - Creating db in another schema? MapSingleType?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM