Search code examples
entity-frameworkentity-framework-6.1

N to M relationship code first does not create the foreign key on the M-table


A SchoolclassCode can have many Pupils.

A Pupil can belong to many SchoolclassCodes.

This is an N to M relation.

I thought N to M relation work in code first by default.

But I also explicitly create the N to M relation here:

    modelBuilder.Entity<SchoolclassCode>().
                  HasMany(c => c.Pupils).
                  WithMany(p => p.SchoolclassCodes).
                  Map(
                   m =>
                   {
                       m.MapLeftKey("SchoolclassCodeId");
                       m.MapRightKey("PupilId");
                       m.ToTable("SchoolclassCodePupil");
                   });

public class SchoolclassCode
    {
        public SchoolclassCode()
        {
            Pupils = new HashSet<Pupil>();
            Tests = new HashSet<Test>();
        }

        public int Id { get; set; }
        public string SchoolclassCodeName { get; set; }
        public string SubjectName { get; set; }
        public int Color { get; set; }
        public string ClassIdentifier { get; set; }
        public ISet<Pupil> Pupils { get; set; }
        public ISet<Test> Tests { get; set; }
        public Schoolyear Schoolyear { get; set; }
        public int SchoolyearId { get; set; }
    }

public class Pupil
    {
        public Pupil()
        {
            PupilsTests = new HashSet<PupilTest>();
            SchoolclassCodes = new HashSet<SchoolclassCode>();
        }

        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Postal { get; set; }
        public string City { get; set; }
        public string Street { get; set; }
        public ISet<PupilTest> PupilsTests { get; set; }
        public ISet<SchoolclassCode> SchoolclassCodes { get; set; }
    }

On the Pupil Table no foreign key is created at all, Why this?


Solution

  • For a many to many relationship, there is no foreign key on either side. The foreign keys are on the join table, which you have mapped to the table SchoolclassCodePupil:

    modelBuilder.Entity<SchoolclassCode>().
                 HasMany(c => c.Pupils).
                 WithMany(p => p.SchoolclassCodes).
                 Map(m =>
                     {
                         m.MapLeftKey("SchoolclassCodeId");
                         m.MapRightKey("PupilId");
                         m.ToTable("SchoolclassCodePupil");
                     });
    

    Entity Framework uses that junction table to determine what belongs in the somePupil.SchoolclassCodes set.