开发者

nHibernate Save One-To-Many

I have a parent class that contains a list of children. I have the parent and child mapped bidirectional with a has-many and an inverse on the parent with cascade.all turned on. If I modify an object in the child list, but no property on the parent, nHibernate does not save the child. If I modify a property on the parent everything saves 开发者_如何学JAVAfine. Is this by design or is there a special property I need to set?


This might have something to do with the way you are adding the children to the collection. In a bidirectional, you have to manage both sides of the relationship in the code. Consider the example from the Fluent Nhibernate Getting Started Guide. Check the Store Entity.

A Store has many Employees. The Staff property of Store is collection of Employees. The relationship is setup as bidirectional.

Store has the following method

public virtual void AddEmployee(Employee employee)
{
  employee.Store = this;
  Staff.Add(employee);
}

As you can see, the childs Parent property needs to be set to the parent object. If this is not done, then Nhibernate will not be able understand who the parent of the child is and cannot automatically save the child if only the child is modified and the SaveOrUpdate(parent) is called.

You need to do both.


I figured it out. I was testing auditing using various listners. When I attached to the IFlushEntityListner it caused saves to stop working. Geez that was frustrating. Thanks everyone!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜