I have a many-to-many association in EF Code-First (as explained in this question), and I want to use a one-to-many to the same entity as well. The problem is EF does not produce the right database scheme. Code:
public class A
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<B> ObjectsOfB { get; set; }
}
public class B
{
public int Id { get; set; }
public virtual A ObjectA { get; set; }
public virtual ICollection<A> OtherObjectsOfA { get; set; }
}
When I remove the ObjectA property of class B the many-to-many association is generated correctly.
When generated incorrectly, entity B gets 2 foreign keys to A, and entity A gets 1 foreign key to B (like a many-to-one relation).
If you have more than one navigation property refering to the same entity EF does not know where the inverse navigation property on the other entity belongs to. In your example: Does
A.ObjectsOfBrefer toB.ObjectAor toB.OtherObjectsOfA? Both would be possible and a valid model.Now, EF does not throw an exception like “cannot determine relationships unambiguously” or something. Instead it decides that
B.ObjectArefers to a third endpoint inBwhich is not exposed as navigation property in the model. This creates the first foreign key in tableB. The two navigation properties inBrefer to two endpoints inAwhich are also not exposed in the model:B.ObjectAcreats the second foreign key in tableBandB.OtherObjectsOfAcreates a foreign key in tableA.To fix this you must specify the relationships explicitely.
Option one (the easiest way) is to use the
InversePropertyattribute:This defines that
A.ObjectsOfBis part of a many-to-many relation toB.OtherObjectsOfA.The other option is to define the relationships completely in Fluent API: