Reza
Reza

Reputation: 5634

EF issues with 2 foreign keys going to same table

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?

Upvotes: 1

Views: 1493

Answers (1)

Morteza Manavi
Morteza Manavi

Reputation: 33216

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

Upvotes: 2

Related Questions