Search code examples
entity-frameworkef-code-firstmany-to-manyentity-framework-migrationsself-referencing-table

EF 6 Code First Many to many With Payload and self referencing many to many


I Have the problem where i have a many to many relationship and on one of the tables there will be a self referencing many to many.

So basically a school have zero or many groups and many groups can have 0 or many schools. The groups table will contain a parent child many to many with itself because a group can be a child of another group or it can have no children and that child can have a child, one child can also have many parents or a entity can have no parents.

I created a mapping table with Payload to solvethe first many to many problem. code snippet

public class School
{
  public virtual ICollection<SchoolGroupMap> SchoolGroupMaps
}

public class SchoolGroup
{
  public virtual ICollection<SchoolGroupMap> SchoolGroupMaps
}

public class SchoolGroupMap
{
  public virtual School School
  public virtual SchoolGroup SchoolGroup
}

i Then tried modifying the code the following way for the the self referencing many to many

public class SchoolGroup
{
  public virtual ICollection<SchoolGroupMap> SchoolGroupMaps

  public virtual ICollection<SchoolGroup> Parents


  public virtual ICollection<SchoolGroup> Children

}

I changed the context with has many and an auto mapping table (forgive me i have been trying so many things today i do not have the exact code). I received an error the properties on the classes must match.

Can anyone help please.

I want to do create navigation properties on the self referencing many to many. Also a seed example would be appreciated

regards


Solution

  • You dont need 3 entities, let do it step by step

    Step 1 :Many to Many relation with school and group

    public class School
    {
      public virtual ICollection<SchoolGroup> SchoolGroups;
    }
    
    public class SchoolGroup
    {
      public virtual ICollection<School> Schools;
    }
    

    Step 2: Self referenced school group

    public class SchoolGroup
    {
      public virtual ICollection<School> Schools;
      public virtual ICollection<SchoolGroup> SchoolGroups;
    }