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

发布于 2024-12-05 12:15:23 字数 595 浏览 5 评论 0原文

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

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 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#.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

也只是曾经 2024-12-12 12:15:23

您将需要创建一个继承自 EntityTypeConfiguration 的类class,如下所示:

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

然后您可以将配置类加载为上下文的一部分,如下所示:

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

本文详细介绍了如何使用配置类。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文