Meta
Meta

Reputation: 489

Defining a many-to-many relationship referencing the same table (EF7/core)

The model has item entities. And there will be items that are dependent on (using) other items. Many-to-many relationship. Example:

Item A is used by Item B, C, and F.
Item B is used by Item C, F and H.

How one would correctly define directional relationships between different items?

The Item:

public class Item
    {
    public int Id
        { get; set;}
    public string Name
        {get; set;}
    }

My first approach to define the dependencies would be:

public class ItemDependency
{
    [Key]
    public int Id
    { get; set; }

    [ForeignKey("ItemParentId")]
    public Item ItemParent { get; set; }

    public int ItemParentId{ get; set; }

    [ForeignKey("ItemDependentId")]
    public Item ItemDependentId { get; set; }

    public int ItemDependentId { get; set; }

}

Upvotes: 2

Views: 598

Answers (1)

Thomas
Thomas

Reputation: 29522

According to the documentation EF7 Many-to-many relationship:

Many-to-many relationships without an entity class to represent the join table are not yet supported. However, you can represent a many-to-many relationship by including an entity class for the join table and mapping two separate one-to-many relationships.

Upvotes: 1

Related Questions