简体   繁体   English

EF Core 中实体之间的多重关系

[英]Multiple relations between entities in EF Core

Let's start with a textbook example for Blogs and Posts using code-first EntityFramework Core:让我们从使用代码优先的 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; }
}

The EF Core configurures the one-to-many relationship automatically by convension, or it can be done manually using fluent API: EF Core 通过约定自动配置一对多关系,也可以使用 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);
    }
}

Fine.美好的。 Now I would like to add an optional FeaturedPost to a Blog .现在我想在Blog中添加一个可选的FeaturedPost

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

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

What would be the recommended way of configuring such additional relationship (preserving the original one-to-many relationship) in EF Core?在 EF Core 中配置这种附加关系(保留原始的一对多关系)的推荐方法是什么? Automatic confuguration results in exception and I fail to figure out how to achieve this manually.自动配置会导致异常,我无法弄清楚如何手动实现这一点。

You could take a look to this other answer of mine.你可以看看我的另一个答案

But, in short, if you have multiple relationships between two types you will need to configure them using the Fluent API.但是,简而言之,如果您在两种类型之间有多种关系,则需要使用 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.

    }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM