i have x which an object of type objectX which has a property ListOfObjectYs thats a
List<objectY>
the nhibernate mapping looks like this:
public ObjectXMap()
{
HasMany(x => x.ListOfObjectYs).AsBag().Inverse();
}
when i go to save it, i change some properties on objectX and then have:
Session.SaveOrUpdate(x);
now i need to update this property that is a list. I get a new list of objectYs and i want to replace the existing list of objectY with a new list. do i need to do this?
foreach (ObjectY y in x.ListOfObjectYs)
{
Session.Delete(y);
deleted = true;
}
if (deleted)
{
_session.Flush();
}
x.ListOfObjectYs.Clear();
foreach (ObjectY y in newObjectYList)
{
x.ListOfObjectYs.Add(y);
Session.SaveOrUpdate(y);
}
_session.Flush();
my questions are:
- Do i have to delete everything and flush before adding new ones.
- Do i need to do all of these incremental saves in between
is there a better way of doing this update where i need to update an object (properties) but also update properties that are list where there is a whole new list (meaning that items need to be deleted and added).
The answers to your questions are no and no. If you want to replace the list you should clear it and add new items. If you have cascade set to all-delete-orphan, as in James Kovacs’ answer, then the changes to the collection will be persisted when the session is flushed.
It’s important to understand what Save, Update, and SaveOrUpdate mean in NHibernate:
See also Manipulating Persistent Data.
Assuming that all your objects were loaded in the same session then replacing a collection may be as easy as: