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

时间:2015-06-12 23:59:43

标签: entity-framework entity-framework-6.1

SchoolclassCode可以有很多学生。

Pupil可以属于许多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上根本没有创建外键,为什么会这样?

1 个答案:

答案 0 :(得分:0)

对于多对多关系,任何一方都没有外键。外键位于连接表上,您已将其映射到表SchoolclassCodePupil

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

实体框架使用该联结表来确定somePupil.SchoolclassCodes集合中的内容。