处理 NHibernate 父子集合的最佳实践 [英] Best practice for Handling NHibernate parent-child collections
问题描述
所以在一个典型的模型中,你有一个可以有很多孩子的父母和一个只能有一个父母的孩子,你如何管理孩子的添加.我一直在使用这种方法;
So in a typical model where you have a parent that can have many children and a child that can have only one parent, how do you manage the adding of children. I have been using this approach;
public class Parent
{
public Parent()
{
Children = new List<Child>();
}
public IList<Child> Children
{
get;
private set;
}
}
public class Child
{
public Parent Parent
{
get;
set;
}
}
var child = new Child();
var parent = new Parent();
parent.Children.Add(child);
child.Parent = parent;
问题是,我想在任何地方添加一个新孩子,我都必须记住添加对孩子和父母的引用,这有点痛苦.我可以向父类添加一个 AddChild 方法,并使其负责添加子类 - 现在的问题是有两种方法可以通过 Children 属性和方法添加子类.那么这是一个更好的解决方案吗?
Problem is that everywhere i want to add a new child i've got to remember to add a reference to both the child and parent and its a bit of a pain. I could just add an AddChild method to the parent class and make that responsible for adding children - the problem now is that there is 2 ways to add a child, through the Children property and the method. So is this a better solution?
public class Parent
{
public Parent()
{
children = new List<Child>();
}
private IList<Child> children
{
get;
private set;
}
public IEnumerable<Child> Children
{
get
{
return children;
}
}
public void AddChild(Child child)
{
children.Add(child);
child.Parent = this;
}
}
是否有关于这方面最佳实践的指南,您会怎么做?
Are there any guidences for best practices on this, and what do you do?
推荐答案
我就是这样做的,只是我不使用私有列表的属性
I do it like that except that I don't use property for private list
private IList<Child> _children
public IEnumerable<Child> Children
{
get
{
return children;
}
}
这篇关于处理 NHibernate 父子集合的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!