【问题标题】:EF issues with 2 foreign keys going to same table2个外键进入同一个表的EF问题
【发布时间】:2016-09-06 04:03:25
【问题描述】:

使用新的 ASP.NET Core 和 Entity Framework 7.0 RC1 Final。我有两个领域,标准和学生之间存在一对多的关系。如果我只有一个 FK 和 Navigation Key,则代码可以正常工作,但是当我添加第二个 FK(Standard2)和 Nav 字段(Students2)时,我收到以下错误消息: InvalidOperationException:实体类型“TestProject.Models.Standard”上的导航“Students”尚未添加到模型中,或被忽略,或目标 entityType 被忽略。

    public class Standard
{
    public Standard()
    {

    }

    public int StandardId { get; set; }
    public string StandardName { get; set; }

    public IList<Student> Students { get; set; }
    public IList<Student> Students2 { get; set; }

}

    public Student()
    {

    }
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public byte[] Photo { get; set; }
    public decimal Height { get; set; }
    public float Weight { get; set; }

    //Foreign key for Standard
    public int StandardId { get; set; }
    public int StandardId2 { get; set; }

    [ForeignKey("StandardId")]
    public Standard Standard { get; set; }

    [ForeignKey("StandardId2")]
    public Standard Standard2 { get; set; }
}

如何在 EF 7 中为同一张表添加两个 FK?

【问题讨论】:

    标签: entity-framework asp.net-core entity-framework-core


    【解决方案1】:

    问题是您需要使用InverseProperty 属性指定关系的另一端,EF 无法自行推断,因此会引发异常:

    public class Standard
    {
        public int StandardId { get; set; }
        public string StandardName { get; set; }
    
        [InverseProperty("Standard")]
        public IList<Student> Students { get; set; }
    
        [InverseProperty("Standard2")]
        public IList<Student> Students2 { get; set; }
    }
    


    或者您可以使用 fluent API 实现相同的结果:

    modelBuilder.Entity<Standard>()
        .HasMany(s => s.Students)
        .WithOne(s => s.Standard)
        .HasForeignKey(s => s.StandardId);
    
    modelBuilder.Entity<Standard>()
        .HasMany(s => s.Students2)
        .WithOne(s => s.Standard2)
        .HasForeignKey(s => s.StandardId2);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-11
      • 2015-07-16
      相关资源
      最近更新 更多