Fluent NHibernate mapping as Bag or as List? What are the differences?
What's the best practice to map to a list of entities that need to开发者_如何学运维 be managed by their parent?
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.
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.
精彩评论