基本C#代码对于多对多关系的建模是什么样的,关系本身具有属性?在这种情况下,多对多也是参考。因此,一个可能的数据库模型可能如下所示(仅举一个我正在谈论的例子)
答案 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}},Children
或Parents
的后续调用将自动检查Node
以确定孩子,父母或所有人关系。