How can I create multiple relationships to the same table in EF7(Core)?

c# entity-framework-core

Question

I'm trying to construct a migration, but it's stumbling over the following class:

public class Unit
{
    public int UnitID { get; set; }
    ...
    public Nullable<int> PreviousUnitID { get; set; }

    [ForeignKey("PreviousUnitID")]
    public Unit PreviousUnit { get; set; }

    public Nullable<int> SubsequentUnitID { get; set; }

    [ForeignKey("SubsequentUnitID")]
    public Unit SubsequentUnit { get; set; }
}

"The navigation property '' cannot be added to the entity type 'Unit' because a navigation property with the same name already exists on entity type 'Unit'.

I'm assuming this slightly peculiar navigation is to blame so I've left out the rest of the class. Does anyone know of a way I can circumvent this issue?

Thanks!

Accepted Answer

This is a known problem with RC1.

Issue:

Development Chain: https://github.com/aspnet/EntityFramework/pull/4239

rowanmiller commented 8th January

That would be #4069 which is fixed in our nightly builds and will ship in RC2.


Popular Answer

Use the virtual keyword:

public virtual Unit PreviousUnit { get; set; }
public virtual Unit SubsequentUnit { get; set; }

Complete code:

public class Unit
{
public int UnitID { get; set; }
...
public Nullable<int> PreviousUnitID { get; set; }

[ForeignKey("PreviousUnitID")]
public virtual Unit PreviousUnit { get; set; }

public Nullable<int> SubsequentUnitID { get; set; }

[ForeignKey("SubsequentUnitID")]
public virtual Unit SubsequentUnit { get; set; }
}

This also enables lazy loading of the Units.

edit: Maybe this could also help: https://github.com/aspnet/EntityFramework/issues/3911



Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why