views:

408

answers:

2

I'm having a problem with a pretty simple setup in NHibernate. (I'm using Fluent Nhibernate)

I have two objects as follows, setup with a bi-directional many-to-many mapping.

Project

-- Categories (IList)

Category

-- Projects (IList) -- Inverse = True

This models as expected in the db.

If I try to delete a project NHibernate performs the delete in the many-to-many table then deletes the project as expected.

However, if I try to delete a category NHibernate throws an exception that it would violate a foreign key constraint.

I've experimentet with inverse="true" on both sides but the exception is thrown either when I try to delete a Project or a Category (depending on where inverse="true" is).If I remove inverse="true" from both sides the delete works as expected on either end. But this causes double entries when saving and updating.

Can anyone tell me where I am going wrong?

+1  A: 

Is it possible that you're not synching up your entire object graph? The schema you show suggests that Project has a collection of Categories, and Category has a collection of Projects. Hibernate expects you to keep the associations in synch within your object graph. In order to delete a Category (for example), try first clearing its projects collection, and removing that category from the "categories" collections of any projects it was associated with.

RMorrisey
I'm not explicitly clearing the collection before syncing up. Although this may work I'm not sure why I would need to do that at one end of the relationship and not the other. Surely I should be able to just remove the project, and NHib will clear any many-to-many columns related to that project. The objects are not tighly bound, it's possible to have projects and categories that exist with no many-to-many relationships.
WDuffy
The underlying SQL doesn't have a concept of who owns the relationship. If you have a two-sided association, Hibernate only needs info from one side. I *believe* that Hibernate's implementation ignores the side marked with inverse="true" on saving/updating - this would explain why it works one way and not the other. Think of what you are doing as deleting entries from the mapping table before you delete the object. Try it at any rate, and see if it fixes your problem.
RMorrisey
Thank's for the help RMorrisey. Does this mean that I should assess and clear all relationships manually in my business logic before committing any NHIb updates? I can't use Cascase All/Delete etc in many-to-many relationships as it removes everything when it could have other relations. I've not had the chance to try it yet (too much work!).
WDuffy
@WDuffy: As far as I can tell in some recent testing, you must manually handle all relationships in your business model before committing.
snicker
A: 

whats the use of nhibernate then?????

peter