Creating a self-referencing Many to Many relationship in Entity Framework 7

asp.net-core c# entity-framework entity-framework-core

Question

I'm attempting to set up my database using the Entity Framework 7 fluent API to add a self-referencing many-to-many relationship. The class in question looks like:

public class Definition
{
    // Some properties
    public virtual ICollection<Definition> AllowedChildDefinitions { get; set; }
}

where the intended relationship is that each definition can have an arbitrary amount of children, of any instance. I would expect a separate table with parent/child columns, where each parent can have multiple children, and each child can be on multiple parents.

There are examples of many-to-many, and examples of self-referencing tables, but I can't work out how to combine the two.

1
7
6/6/2016 9:09:19 AM

Popular Answer

The workaround is to map the join table to an entity. Please look into this.

public class Definition
{
   public int Id { get; set; }
   public ICollection<ChildrenDefinition> ChildrenDefinitions{ get; set; }
}

public class ChildrenDefinition
{
  public int DefinitionId { get; set; }
  public Definition Definition { get; set; }

  public int ChildrenId { get; set; }
  public Children Children { get; set; }
}

public class Children
{
    public int Id { get; set; }
    public ICollection<ChildrenDefinition> ChildrenDefinitions{ get; set; }
}

Be sure to configure ChildrenDefinition with a composite key:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<ChildrenDefinition>().HasKey(x => new {  x.DefinitionId, x.ChildrenId });
}

To navigate, use a Select:

// Children.Definition
var definitions = Children.ChildrenDefinitions.Select(c => c.Definition);

Hope this may help you out!

0
6/7/2016 10:10:49 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