Using NHibernate, I am looking for a way to automatically update persisted collections when a persisted item is deleted. For instance:
var post = GetNewPost();
var blog = GetCurrentBlog();
blog.Posts.Add(post);
BlogRepository.Update(blog);
User.Posts.Add(post);
UserRepository.Update(user);
----
// Somewhere else
var blog = GetCurrentBlog();
var post = blog.Posts.Last();
blog.Posts.Remove(post);
NHibSession.Flush(); // Throws an ObjectDeletedException due to 'post'
// still being in the User.Posts collection
I understand that there may be issues with the model and/or mapping in this example, but those issues aside, I want to find a way to get the User.Posts collection to automatically be updated, i.e. remove 'post' from itself. (Maybe not the greatest example in the world, but assume there are many Blogs and many Users, unrelated to one another except through Posts. Understand that this is a façade.)
In this example, I'm using only one NHibernate session. I'm willing to adjust that, but I'm looking for a scheme, and it should be transparent to the model. NHibernate events are also on the table if it can be shown to be a good practice.
I believe that LINQ to SQL can handle this situation, so I'm a little surprised that NHibernate can't (to the best of my searching abilities). Are there any supplementary frameworks available which can?
Here are the relevant mappings for this example:
<class name="App.Core.Domain.Post, App.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="Posts" xmlns="urn:nhibernate-mapping-2.2">
<id name="Id" type="Guid" column="PostId">
<generator class="assigned" />
</id>
...
<many-to-one cascade="save-update" access="field.pascalcase-underscore" name="Blog" column="BlogId" />
<many-to-one cascade="save-update" access="field.pascalcase-underscore" name="User" column="UserId" />
</class>
<class name="App.Core.Domain.Blog, App.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="Blogs" xmlns="urn:nhibernate-mapping-2.2">
<id name="Id" type="Guid" column="BlogId">
<generator class="assigned" />
</id>
...
<bag name="Posts" cascade="all" inverse="true" access="field.pascalcase-underscore">
<key column="PostId" />
<one-to-many class="App.Core.Domain.Post, App.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</bag>
</class>
<class name="App.Core.Domain.User, App.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="Users" xmlns="urn:nhibernate-mapping-2.2">
<id name="Id" type="Guid" column="UserId">
<generator class="assigned" />
</id>
...
<bag name="Posts" cascade="all" inverse="true" access="field.pascalcase-underscore">
<key column="PostId" />
<one-to-many class="App.Core.Domain.Post, App.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</bag>
</class>