开发者

Entity Framework Code First - Configuration in another file

开发者 https://www.devze.com 2023-04-06 11:37 出处:网络
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?

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?

Wh开发者_运维百科at 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#.


You will want to create a class that inherits from the EntityTypeConfiguration class, like so:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消