【问题标题】:N to M relationship code first does not create the foreign key on the M-tableN to M 关系代码首先不在 M-table 上创建外键
【发布时间】:2015-06-12 23:59:42
【问题描述】:

一个 SchoolclassCode 可以有许多学生。

一个学生可以属于许多 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; }
    }

在瞳孔表上根本没有创建外键,为什么会这样?

【问题讨论】:

    标签: entity-framework entity-framework-6.1


    【解决方案1】:

    对于多对多关系,任何一方都没有外键。外键位于连接表上,您已将其映射到表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 使用该联结表来确定 somePupil.SchoolclassCodes 集中的内容。

    【讨论】:

    • 啊我完全忘记了连接表上的 FK 和级联删除不起作用...谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多