LeftyX
LeftyX

Reputation: 35587

NHibernate and collection types


I am trying to develop my very first project with Nhibernate 3.0. I've gone through loads of material (blogs, papers and samples) and I think I can understand the basics, pretty much.
I think I've understood the meaning of different types of collection but than when I see the examples found on the Internet I think I haven't really understood.
The documentation says that you should use a Set when you do not want duplicates and a List/Bag when you want to allow duplicates. Most of the samples I have found are based on a typical situation where you have Orders/OrderLines. If I have a look the mapping file of the Order I can see something like this:

<class name="OrderHeader"
        table="Orders">
    <id name="OrderId">
        <generator class="hilo"/>
    </id>
    <property name="OrderDate"/>
    <bag name="OrderItems" table="OrderDetails" cascade="all" inverse="true">
        <key column="OrderId"/>
        <one-to-many class="OrderDetail"/>
    </bag>
</class>

<class name="OrderDetail"
        table="OrderDetails">
    <id name="DetailId">
        <generator class="hilo"/>
    </id>
    <many-to-one name="ProductOrdered" column="ProductId"/>
    <many-to-one name="Order" column="OrderId" />
</class>

I had expcted to see the OrderItems mapped as a Set; an order will have unique OrderItems?
Am I right? At the same time I would expect to find a mapping for the class Product a bag of OrderItems

...  

<bag lazy="true" name="OrderItems">
  <key foreign-key="FK_OrderItems_Products">
    <column name="ProductCode" />
  </key>
  .....  
</bag>

...  

In this situation a product would have a list of non-unique OrderItems.
Is there anything am I missing?
Forgive me all for the silly question :-s

Upvotes: 2

Views: 1936

Answers (3)

Goblin
Goblin

Reputation: 8022

I would set it as a <list ...> as in my book two orderlines with the same characteristics are identical (.Equals should return true) - also, many consider the order(!) of orderlines to be important. :-)

Upvotes: 2

Jamie Ide
Jamie Ide

Reputation: 49251

The reason for this is that bag mapping is compatible with a .NET IList<T> mapping as Yads answered. Collections are typically mapped that way to avoid having to reference Iesi.Collections in your classes.

With NHibernate 2.1, you can use set mapping by declaring the collection as ICollection<T> and initializing it as a HashSet<T>. Using NHibernate 3 I believe you can declare the collection as ISet<T>.

I agree most real world collections should be mapped as sets.

Upvotes: 1

Vadim
Vadim

Reputation: 17957

The reason most people implement it as a bag is because they can use the built in List<> class or IList<> interface to represent their collection.

Upvotes: 0

Related Questions