实体框架代码优先 - 在另一个文件配置 [英] Entity Framework Code First - Configuration in another file

查看:142
本文介绍了实体框架代码优先 - 在另一个文件配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对表的映射使用流利API,因此,它是所有在一个单独的类并分离的实体不内嵌在OnModelCreating方法

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?

我目前在做什么:

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);
    }
}



你怎么做到这一点?我使用C#

How do you do this? I am using C#.

推荐答案

您将要创建一个从的EntityTypeConfiguration 类,如下所示:

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文章进入更详细的关于使用配置类。

This article goes into greater detail on using configuration classes.

这篇关于实体框架代码优先 - 在另一个文件配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆