views:

48

answers:

2

whats the best practice to map to a list of entities that need to be managed by their parent

A: 

All the examples I've found use IList<>, and that's what I use in my code.

I think Bag may be a leftover from the original Java Hibernate - I vaguely remember reading a posting to that effect.

Tom Bushell
+2  A: 

Difference is semantic:

  • a set should be used, when your collection is unordered and can contain each item only once
  • a bag is still unordered, however - it can contain some items many times (well - at least with many-to-many mappings)
  • a list is a collection that is ordered and can contains some items many times - you have a guarantee, that items will be retrieved in the same order as they were saved (NHibernate will manage specified index column for you)

However, both bag and list can be represented with IList<> in code - that's perfectly ok, but you have to remember that you cannot rely on order of items in a bag.

When choosing how to map your list, choose the option that best matches your collection - if you don't need order, choose bag, if you need order - choose list.

Sidenote: there's a possibility to control order of items in bag - you have to specify order-by attribute with appropriate sql expression. However do not use this to emulate list behavior - use list directly. Order-by attribute for bags is meant to be used, when order is a result of some other attributes - like ordering of entities by timestamp of last modification.

maciejkow

related questions