简体   繁体   English

如何在EF7(Core)中为同一表创建多个关系?

[英]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 编辑:也许这也可以帮助: https : //github.com/aspnet/EntityFramework/issues/3911

This is a known problem with RC1. 这是RC1的已知问题。

Issue: 问题:

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

rowanmiller commented 8th January Rowanmiller于1月8日评论

That would be #4069 which is fixed in our nightly builds and will ship in RC2. 那将是#4069,它将在我们的每晚版本中固定,并将在RC2中发货。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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