EF issues with 2 foreign keys going to same table

asp.net-core entity-framework entity-framework-core

Question

Using the new ASP.NET Core and Entity Framework 7.0 RC1 Final. I have two fields with a one-to-many relationship between Standards and Students. If I just have the one FK and Navigation Key the code works just fine, but when I add in the second FK (Standard2) and Nav field (Students2) I get the following error message: InvalidOperationException: The navigation 'Students' on entity type 'TestProject.Models.Standard' has not been added to the model, or ignored, or target entityType ignored.

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

How do I have two FK's to the same table in EF 7?

1
1
5/11/2016 12:17:40 AM

Accepted Answer

The problem is that you need to specify the other end of your relationships by using InverseProperty attribute, something that EF cannot infer on its own and hence throws an exception:

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


Or you can achieve the same results by using 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);
2
5/11/2016 1:56:01 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow