【问题标题】:Representing Graph in EF Code-First在 EF Code-First 中表示图形
【发布时间】:2012-11-24 16:18:01
【问题描述】:

我试图在实体框架代码优先模型中表示具有类型边的图。我很难理解如何正确建立关系。我将图中的节点称为“项目”,将边称为“关系”这是我所拥有的:

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; }
}

这就是我得到的:

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

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

【问题讨论】:

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


    【解决方案1】:

    您可以使用[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; }
    }
    

    【讨论】:

    • 哇,这么简单,对吧?非常感谢,效果很好!
    猜你喜欢
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多