EF发出2个外键转到同一个表

时间:2016-05-11 00:17:40

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

使用新的ASP.NET Core和Entity Framework 7.0 RC1 Final。我有两个领域,标准和学生之间有一对多的关系。如果我只有一个FK和导航键,代码工作正常,但当我添加第二个FK(Standard2)和导航字段(Students2)时,我收到以下错误消息: InvalidOperationException:导航'学生'在实体类型' TestProject.Models.Standard'尚未添加到模型中,或忽略,或忽略目标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?

1 个答案:

答案 0 :(得分:2)

问题是您需要使用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; }
}


或者您可以使用流畅的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);