NHibernate: how to save a new object without overwriting the parent:

I am wondering what better design would be to continue a new child with NHibernate without accidentally overwriting the parent in the database.

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

class Child { Parent Parent; // other fields } 

My problem is that the child was provided from the user interface level along with the parent ID, which means that Parent ref is basically uninitialized: it will have an identifier, but everything else is zero - because the only way to fill in its fields was It would be an extra trip to the database to read them.

Now, if I call Session.SaveOrUpdate(child) in NHibernate, what happens to the parent. I do not want NHibernate to cascade with the exception of an uninitialized parent, as that would simply destroy the data in the database. How do people approach this problem? Any best practices?

+4
source share
4 answers

If your models look like

 class Parent { } class Child { Parent myParent; } 

and you are trying to set the parent element and save it without the full parent object, but only the identifier.

You can try the following:

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

before saving, this should tell nhibernate that no changes to the parent are saved, and it should only look at the object so that Id maintains the connection between the parent and the child

0
source

You must use session.Load (parentid) to get the common root. Unlike the session.Get () method, this does not actually extract data from the database, but simply creates a parent proxy object used to add children to the correct parent in the database (for example, enter the foreign key correctly).

Your code will probably look something like this:

 // 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 that Get / Load and nhibernate caching are really good

+3
source

You should probably work with an aggregated root (possibly with a parent) when doing Saves (or SaveOrUpdates, etc.).

Why not just:

  • Get the parent using the parent id that your child has from the user interface layer.
  • Add a child to the parent's children collection
+1
source

I think you need to view the display configuration for nhibernate. If you reference a parent to a parent that must execute Cascade all, it will update it! Therefore, if you say Cascade.None , it will not do anything. All the rest are bad ideas. Because you already have this parent's information. So why read from db agane ?!

+1
source

All Articles