开发者

NHibernate: How to save a new entity without overwriting the parent:

I'm wondering what the best design would be for persisteing a new child entity with NHibernate without accidentally overwriting the parent in the datab开发者_如何学Pythonase.

The problem I have is that the child entity will look something like this:

class Child
{
    Parent Parent; 
    // other fields
}

My problem is that the child has been supplied from the UI layer along with the ID of the parent, and that means that the Parent ref is basically uninitialized: It will have the ID populated but everything else null - because the only way to populate its fields would be an extra round trip to the database to read them.

Now if I call Session.SaveOrUpdate(child) on NHibernate, what's going to happen with the parent. I don't want NHibernate to cascade save the uninitialized parent since that would just destroy the data in the database. How would people approach this problem? Any best practices?


You must use the session.Load(parentid) to get the aggregate root. In contrast to the session.Get() method, this does not actually fetch any data from the database, it just instantiates a Parent proxy object used to add Child objects to the correct Parent in the DB (eg. get the foreign key correctly).

Your code would probably look something like:

// Set the Parent to a nhibernate proxy of the Parent using the ParentId supplied from the UI
childFromUI.Parent = Session.Load<Parent>(childFromUI.Parent.Id);
Session.Save(childFromUI);

This article explains Get/Load and the nhibernate caches really well


You should probably be working with the aggregate root (probably the Parent) when doing Saves (or SaveOrUpdates etc).

Why not just:

  • Fetch the parent object using the parent id you have in the child from the UI layer
  • Add the child to the parents 'children' collection


I think you have to overview your mapping configuration for nhibernate. If you have defined on the reference by the child to the parent that hi has to Cascade all, it will update it! So if you say Cascade.None he will do nothing. All other are bad ideas. Because you allready has the information of this parent. So why read from db agane?!


If your models looks like this

class Parent 
{

}


class Child
{
     Parent myParent;
}

and you are trying to set the parent and save the child without having a full parent object, just the ID.

You could try this:

session.Lock(child.myParent, LockMode.None); 

before saving, this should tell nhibernate that there are no changes to the parent object to persist and it should only look at the object for the Id to persist the association between Parent and Child

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜