I want to be able to create a parent object with children and let the parent handle the update, saves and deletes.
My map classes.
ParentMap
Id(x => x.Id, "ID").GeneratedBy.Identity();
Map(x => x.Name);
HasMany(x => x.Children)
.KeyColumn("ParentID")
.Inverse()
.Cascade
.AllDeleteOrphan()
.AsBag();
ChildMap
Id(x => x.Id, "ID").GeneratedBy.Identity();
Map(x => x.Name);
Map(x => x.Value);
References(x => x.Parent);
This is the code.
After the postback I create a new parent with children. The problem is it won’t delete the children but everything else works fine update and saves.
var parent = new Parent();
parent.Id = _view.parentID;
parent.Name = _view.Name;
parent.Children = _view.Children;
I’ve also tried the code below but this returns a nonunique error.
var parent = repository.Get(_view.parentID);
parent.Name = _view.Name;
parent.Chidlren = _view.Children;
Can anyone tell me the best way to deal with this in NHibernate?
Thanks.
You can’t reassign the child collection with NHibernate. NHibernate is basically “watching” the child collection for changes so that it knows how to handle saves to the database. If you reassign the child collection NHibernate looses the reference and can no longer track the changes. To get around this you must modify the child collection but not reassign it.
How I normally ensure this is I make the collection readonly with a private setter. I then add methods to the parent class to modify the list as needed.