多对多关系的类模型,其中关系具有属性

时间:2010-05-06 18:03:23

标签: c# oop many-to-many

基本C#代码对于多对多关系的建模是什么样的,关系本身具有属性?在这种情况下,多对多也是参考。因此,一个可能的数据库模型可能如下所示(仅举一个我正在谈论的例子)

  • 节点
    • ID
    • 名称
    • 描述
  • 关系
    • PARENT_ID
    • Child_ID
    • Relationships_Type

2 个答案:

答案 0 :(得分:1)

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
{
   ....
}

答案 1 :(得分:1)

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
{
    //...
}

最重要(也很容易拙劣)的组件是Relationships类的Node属性。我定义的方式是最简单的方式,但更可靠的方法是以更多数据库方式对其进行建模,其中您有一个中央关系存储库并且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实例,使用Node函数在Add之间添加您的关系,并将完成剩下的工作。对其中一个受影响的Relationships的{​​{1}},ChildrenParents的后续调用将自动检查Node以确定孩子,父母或所有人关系。