我可能在这里做一个新手的错误,但我无法弄清楚如何使这项工作。我有两个实体 - Parent
和Child
,其中一个Parent
可以有许多Child
ren。问题似乎是,当我向父项添加新子项时,父项不能级联保存子项,因为子项实例尚未具有ID。在另一方面,孩子不能在自己的坚持,所以它没有获得一个ID的方式...NHibernate的坚持为了增加对象集合
我的映射:
public ParentMap()
{
// ID and other properties
HasMany(p => p.Children).Cascade.AllDeleteOrphan().Not.LazyLoad();
}
public ChildMap()
{
// ID and other properties
References(c => c.Parent);
}
现在,我可能已经有一个父记录在我的数据库中,并且我想将一个孩子添加到其子集合中。为此,我创建了一个Child
类的新实例,将该子项添加到父项的Children
属性(类型为IList<Child>
)。我还获取父记录并将子女Parent
属性设置为父实体。
当我试图挽救这个,我得到的错误,无论我尝试做顺序。
随着Save(p)
,节约父记录,希望孩子将被保存在级联,我得到以下错误:
Cannot insert the value NULL into column 'ChildID', table 'dbo.Children'; column does not allow null values. INSERT fails. The statement has been terminated.
如果我试着在其他的方式,即先救孩子,然后加入它的母公司和保存的父母,我得到以下错误:
null id in Application.Domain.Entities.Child entry (don't flush the Session after an exception occurs)
按照什么顺序我应该叫parent.Children.Add(child)
,child.Parent = parent
,session.Save(parent)
和session.Save(child)
,使这个工作?我的映射配置中是否缺少某些东西?
更新:我添加.Inverse()
,并尝试没有成功如下:
// First of the above errors
session.Save(child);
child.Parent = parent;
parent.Children.Add(child);
session.Save(parent);
// Second of the above errors
child.Parent = parent;
parent.Children.Add(child);
session.Save(child);
session.Save(parent);
// Second of the above errors
child.Parent = parent;
parent.Children.Add(child);
session.Save(parent);
// Second of the above errors
child.Parent = parent;
parent.Children.Add(child);
session.Save(child);
随着'.Inverse()'如你所说,我仍然得到完全相同的错误。 –