问题描述
我有以下设置:
public class ParentEntity
{
public ICollection<ChildEntity> {get; set; }
}
public class ChildEntity
{
// do i need to the parent here?
}
我设法保存了ParentEntity并将保存级联到添加的子实体,这些子实体也已保存.但是在db表中,将子代的ParentId引用设置为允许NULL.将其设置为NOT NULL时,保存失败,因为子表中的ParentId为NULL.
I managed to save the ParentEntity and cascaded the save to the added child entities which were saved as well. But in the db table the ParentId reference of the child was set to allow NULL. When setting it to NOT NULL the save failes since the ParentId in the child table is NULL.
那里发生了什么? ;)
What's happening there? ;)
何时
推荐答案
您应正常映射关系的两端,并且在将子级添加到父级集合中时,还应在子级上设置父级属性.通常,您可以通过编写如下方法来实现此目的:
You should map both sides of the relationship normally, and when you add a child to the parent's collection, you should also set the parent property on the child. Normally you would achieve this by writing a method like this:
public void AddChild(ChildEntity child)
{
this.Children.Add(child);
child.Parent = this;
}
NHibernate根据ChildEntity类中的映射属性在Child表中保留ParentId列.一对多关系的定义仅允许NHibernate根据此列中的值从数据库加载集合.
NHibernate persists the ParentId column in the Child table based on the mapped property in the ChildEntity class. The definition of the one-to-many relationship merely allows NHibernate to load the collection from the database based on values in this column
这篇关于NHibernate父母/子女关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!