views:

76

answers:

1

Hi, I'm trying to setup a sample project using NHibernate and Fluent NHibernate. I am using the example mappings from the Fluent NHibernate web-site.

My question is about the many-to-many mapping between Store and Product. It seems (when looking at the generated SQL) that when adding a product to the store, NHibernate deletes all the records from the association table (StoreProduct) that belong to that store, and then inserts all the records again, now including the association to the new product I added.

Is this the default behavior or am I missing something? It just seems not very efficient to delete and re-insert all the associations every time I need to add one.

+1  A: 

This is expected behavior. I believe this should only happen when you use the bag mapping strategy which it looks like they are using in the example. A bag indicates that there is an unordered collection that can have duplicate items. Because bag items are not unique NHibernate cannot tell when you've added or removed an item from a bag easily. The easiest thing for NHibernate then is to do is delete all associations and then re-add.

It's been a while since I've played with many-to-many mappings (I usually just map as two one-to-many relationships) but I believe that if you use use a different construct, for example, a set (which does not allow duplicates) you should find that the behavior is different. Of course, you should use what ever construct makes the most semantic sense for your application.

Michael Gattuso
Thanks, using HashSet<T> and changing the mapping to AsSet() on the product collection solved this.
Doron Yaacoby