簡體   English   中英

多對多關系的類模型,其中關系具有屬性

[英]Class model for a many-to-many relationship, where relationship has attributes

基本的C#代碼將為多對多關系建模,該關系本身具有屬性? 而且在這種情況下,多對多是參考。 因此,可能的數據庫模型可能如下所示(僅舉例說明我在說什么)

  • 節點
    • ID
    • 名稱
    • 描述
  • 關系
    • PARENT_ID
    • Child_ID
    • Relationships_Type
public class Node
{
     public int Id {get;set;}
     public string Name {get;set;}
     public string Description{get;set;}
     public Dictionary<RelationShipType,IEnumerable<Node>> ChildNodes {get;set;}
}

public enum RelationShipType
{
   ....
}
public class Node
{
    // General properties

    public List<Relationship> Relationships { get; set; }
}

public class Relationship
{
    public Node Parent { get; set; }
    public Node Child { get; set; }
    public RelationshipType Type { get; set; }
}

public enum RelationshipType
{
    //...
}

其中最重要(且容易被破壞)的組件是Node類上的Relationships屬性。 我定義的方法是最簡單的方法,但是更可靠的方法是采用數據庫的方式對其進行建模,在這種情況下,您擁有一個中央關系存儲庫,並且Node已連接。

public class RelationshipRepository
{
    private List<Relationship> relationships = new List<Relationship>();

    public IEnumerable<Relationship> GetRelationships(Node node)
    {
        return relationships.Where(r => r.Child == node || r.Parent == node);
    }

    public IEnumerable<Relationship> GetChildRelationships(Node node)
    {
        return relationships.Where(r => r.Parent == node);
    }

    public IEnumerable<Relationship> GetParentRelationships(Node node)
    {
        return relationships.Where(r => r.Child == node);
    }

    public void Add(Node parent, Node child, RelationshipType type)
    {
        relationships.Add(new Relationship()
        {
            Parent = parent,
            Child = child,
            Type = type
        });

        parent.RelationshipSource = this;
        child.RelationshipSource = this;
    }
}

public class Node
{
    // General properties

    public RelationshipRepository RelationshipSource { get; set; }

    public IEnumerable<Relationship> Relationships 
    { 
        get { return relationships.GetRelationships(this); }
    }

    public IEnumerable<Relationship> Children
    { 
        get { return relationships.GetChildRelationships(this); }
    }

    public IEnumerable<Relationship> Parents
    { 
        get { return relationships.GetParentRelationships(this); }
    }
}

這將允許您創建一個單獨的RelationshipRepository實例,使用Add函數Add Node之間的關系,其余的工作將由您來完成。 隨后在受影響的Node之一上對RelationshipsChildrenParents調用將自動檢查relationshipSource以確定孩子,父母或所有關系。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM