Multiple One-to-many relationships in the same table. The property is not a valid navigation property on the related type

ef-code-first entity-framework entity-framework-core

Question

I am having difficulty mapping this relationship.

public class Person
{
     public long Id { get; set; }

     [InverseProperty("Friend")]
     public virtual ICollection<Friendship> Friends { get; set; }
}

public class Friendship
{
    public long Id { get; set; }

    public long PersonId { get; set; }
    [ForeignKey(nameof(PersonId))]
    public virtual Person Person { get; set; }

    public long FriendPersonId{ get; set; }
    [ForeignKey(nameof(FriendPersonId))]
    public virtual Person Friend { get; set; }
}

I get the following error

The InversePropertyAttribute on property 'Friends' on type 'Person' is not valid. The property 'Friends' is not a valid navigation property on the related type 'Friendship'. Ensure that the property exists and is a valid reference or collection navigation property.

I can clearly see that Friendship class does contain a property called Friend, but I am not sure what makes it an invalid navigation property.

If I changed my InverseProperty attribute to FriendPersonId it throws a null reference exception.

1
2
2/28/2017 3:03:08 PM

Accepted Answer

The inverse property was set incorrectly.

Should have been [InverseProperty("Person")])

Credit: Ivan Stoev for pointing out my mistake.

1
3/1/2017 1:43:33 PM


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