EF Core 中实体之间的多重关系 [英] Multiple relations between entities in EF Core

查看:16
本文介绍了EF Core 中实体之间的多重关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们从使用代码优先的 EntityFramework Core 的博客和帖子的教科书示例开始:

Let's start with a textbook example for Blogs and Posts using code-first EntityFramework Core:

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public ICollection<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

EF Core 通过约定自动配置一对多关系,也可以使用 fluent API 手动完成:

The EF Core configurures the one-to-many relationship automatically by convension, or it can be done manually using fluent API:

internal class MyContext : DbContext
{
    // ...

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>()
            .HasOne(p => p.Blog)
            .WithMany(b => b.Posts);
            .HasForeignKey(p => p.BlogId);
    }
}

好的.现在我想向 Blog 添加一个可选的 FeaturedPost.

Fine. Now I would like to add an optional FeaturedPost to a Blog.

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public ICollection<Post> Posts { get; set; }
    
    public Post FeaturedPost { get; set; }
}

在 EF Core 中配置这种附加关系(保留原始一对多关系)的推荐方法是什么?自动配置导致异常,我无法弄清楚如何手动实现.

What would be the recommended way of configuring such additional relationship (preserving the original one-to-many relationship) in EF Core? Automatic confuguration results in exception and I fail to figure out how to achieve this manually.

推荐答案

你可以看看这个其他答案我的.

但是,简而言之,如果您在两种类型之间有多个关系,则需要使用 Fluent API 配置它们.

But, in short, if you have multiple relationships between two types you will need to configure them using the Fluent API.

在您的情况下,请尝试以下操作:

In your case, try something like this:

internal class MyContext : DbContext
{
    // ...

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>()
            .HasOne(p => p.Blog)
            .WithMany(b => b.Posts);
            .HasForeignKey(p => p.BlogId);

        modelBuilder.Entity<Blog>()
            .HasOne(x => x.FeaturedPost)
            .WithOne()
            .HasForeignKey<Blog>(b => b.FeaturedPostId); 

        // You should add a int? FeaturedPostId property in your Blog class.
        // Having a nullable FK will make it optional.

    }
}

这篇关于EF Core 中实体之间的多重关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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