简体   繁体   中英

Multiple relations between entities in EF 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; }
}

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

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

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.

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.

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.

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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