N 到 M 关系代码首先不在 M-table 上创建外键

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

一个 SchoolclassCode 可以有很多 Pupils。

一个学生可以属于多个 SchoolclassCodes。

这是一个 N 对 M 的关系。

我认为 N 到 M 关系默认在代码中优先工作。

但我也在这里明确创建了 N 到 M 关系:

    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; }
    }

在 Pupil 上 Table 根本没有创建外键,这是为什么?

对于多对多关系,两边都没有外键。外键在连接 table 上,您已将其映射到 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 使用该连接点 table 来确定属于 somePupil.SchoolclassCodes 集合的内容。