简体   繁体   中英

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

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!

use virtual instead of unit

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

public Virtual PreviousUnit { get; set; }
public Virtual SubsequentUnit { get; set; }
}

create as many relationship as you want

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM