在EF Code-First中表示图形

时间:2012-11-24 16:18:02

标签: entity-framework ef-code-first code-first

我试图在实体框架代码优先模型中表示带有类型边的图。我很难理解如何正确建立关系。我正在调用图表'Items'中的节点和边缘'Relationships'这就是我所拥有的:

public class Item : Learnable
{
    public Boolean IsBeginningItem { get; set; }
    public virtual List<Relationship> RelationshipsLeft { get; set; }
    public virtual List<Relationship> RelationshipsRight { get; set; }
}

-

public class Relationship : Learnable
{
    public Boolean IsPrerequisiteRelationship { get; set; }
    public virtual RelationshipType RelationshipType { get; set; }

    public int ItemLeftID { get; set; }
    [ForeignKey("ItemLeftID")]
    public virtual Item ItemLeft { get; set; }

    public int ItemRightID { get; set; }
    [ForeignKey("ItemRightID")]
    public virtual Item ItemRight { get; set; }
}

这就是我得到的:

enter image description here

如何让Item的RelationshipsRight属性对应于Relationship的ItemLeft属性和Item的RelationshipsLeft属性对应于Relationship的ItemRight属性?

哦......我想我应该解释一下这应该是一个可以双向导航的有向图。 :)

1 个答案:

答案 0 :(得分:0)

您可以使用[InverseProperty]属性将正确的导航属性对绑定在一起:

public class Relationship
{
    //...

    public int ItemLeftID { get; set; }
    [ForeignKey("ItemLeftID"), InverseProperty("RelationshipsRight")]
    public virtual Item ItemLeft { get; set; }

    public int ItemRightID { get; set; }
    [ForeignKey("ItemRightID"), InverseProperty("RelationshipsLeft")]
    public virtual Item ItemRight { get; set; }
}