EF Core - Many to many relationship on same class

c# entity-framework entity-framework-core

Question

What is best way to implement many to many from same class in Entity Framework Core?

In my case Every connection is bidirectional. If Item 'A' has Item 'B' in its "RelatedItems" list, then Item 'B' has Item 'A' in its "RelatedItems" list.

class Item
{
    int Data {get;set}
    List<Item> RelatedItems {get;set;}
}
1
2
7/12/2016 10:44:34 AM

Popular Answer

You have to add the self Referencing Foreign-Key-Relationship as following:

public class Item
{

    public Item()
    {
        RelatedItems = new List<Item>();
    }

    public int ItemId { get; set; }
    public int? ParentItemId { get; set; }
    public Item ParentItem{ get; set; }
    public List<Item> RelatedItems { get; set; }
}

The fluent API:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{ 
 ...
    modelBuilder.Entity<Item> =>
    {
        entity
            .HasMany(e => e.RelatedItems )
            .WithOne(e => e.ParentItem) 
            .HasForeignKey(e => e.ParentItemId );
    });
  ...

}
1
7/12/2016 11:13:27 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow