Krzysiek
Krzysiek

Reputation: 98

Entity Framework: Two foreign keys connected by one collection

I know that there is related topic: two Foreign Keys from same table, but I can't find there fix to my problem. I am pretty new to EF.

I have the following model classes (Code-First):

public class Member
{
    [Key]
    public int MemberID { get; set; }
    public string Name {get; set;}
    public string Surname { get; set; }

    public virtual ICollection<Marriage> Marriages { get; set; }
}

public class Marriage
{
    [Key]
    public int MarriageID { get; set; }
    public string MarriagePlace { get; set; }
    public DateTime MarriageDate { get; set; }

    [ForeignKey("Husband")]
    public int HusbandID { get; set; }
    [ForeignKey("Wife")]
    public int WifeID { get; set; }

    public virtual Member Husband { get; set; }
    public virtual Member Wife { get; set; }
}

My problem is that both Husband and Wife should be connected to the same Marriage collection in Member class. I did that:

    modelBuilder.Entity<Marriage>()
        .HasRequired<Member>(m => m.Husband)
        .WithMany(m => m.Marriages)
        .HasForeignKey(m => m.HusbandID)
        .WillCascadeOnDelete(false);

And husband is now connected to Merriages collection. But everything breaks when I'm trying to add the same thing for Wife property:

    modelBuilder.Entity<Marriage>()
        .HasRequired<Member>(m => m.Wife)
        .WithMany(m => m.Marriages)
        .HasForeignKey(m => m.WifeID)
        .WillCascadeOnDelete(false);

and I am getting an error:

Error 1 Schema specified is not valid. Errors: The relationship 'FamilyTree.Models.Marriage_Husband' was not loaded because the type 'FamilyTree.Models.Member' is not available. C:\Users\Sumiteru\Documents\Visual Studio 2013\Projects\FamilyTree\FamilyTree\App.xaml 9 21 FamilyTree

Upvotes: 0

Views: 107

Answers (1)

ext
ext

Reputation: 128

That error occurs becouse EF didn't know what navigation property he must use. In OnModelBuliding method you are setting a Member's foreign key to Marriages twice, so EF is confused about what navigation property should use when it will populating Marriages and throws an exception.

There's a topic on EF codeplex forum, where user named 'moozzyk' explains that EF behavior more clearly (in comment): Link.

As a solution, You should do another collection navigation property in Member class and map Wife's or Husbend's foreign key to it. You can find the same solution on that SO anwser: Link.

Upvotes: 1

Related Questions