views:

355

answers:

1

I am using Fluent and NHibernate. I have two objects say A & B which has a many-to-many relationship between them. I am using a unidirectional many-to-many mapping when A HasMany B's. There is no reference in B about A (Unidirectional).

This creates a third table (named ABMapping) in the Database which has the two columns relating to primary keys of A & B.

If I delete the object A, the entries from the ABMapping table related to A are deleted. That's cool.

But, now I am not able to delete an object B, as it has a FK constraint. How can I set it up so that on deleting B, all entries related to B in ABMapping are deleted automatically?

+1  A: 

If B doesn't reference A then it doesn't know about the mapping table so it can't cascade the delete. As I see it you have two options:

  1. Cascade the delete in the database using cascading deletes on your FK or a trigger.
  2. Map the relationship from B to A; you don't have to expose it to consumers of your class, the A collection could be mapped as a private field using an access strategy. I always do this for collections (using .Access.CamelCaseField(Prefix.Underscore)) so that I don't expose IList.
Jamie Ide
Thanks for the help Jamie. One more question I now have is that if I use bidirectional mapping, and then delete an object of class B, it should only delete the mapping in the ABMapping table. However, when I tried the Cascade settings as .Delete or .DeleteOnCascade it goes and deletes the object A as well. I also had an Inverse set on the mapping in B.I tried Cascade.None() but i that case it did not delete the mapping in ABMapping and gave me the constraint violation error.
Zuber
@Zuber - My answer was incomplete. You shouldn't use NH cascade with many-to-many. You need to remove the B object from A's collection of Bs (this removes the links), then delete the B object. I think if you go this route you will not need to map the A collection in B but you'll probably want to so that you have a reference to the A objects that reference the B object.
Jamie Ide

related questions