Mapping Collections in NHibernate

A Set is a collection of distinct objects considered as a whole. A valid example of a set (of letters) is: { a, b, c, d }. Each letter occurs exactly once.

A Bag is a generalization of a set. A member of a bag can have more than one membership while each member of a set has only one membership. A valid example of a bag is { a, a, a, b, c, c, d, …}. The letters a and c appear more than once in the Bag.

A Map (also called associative container, hash, dictionary, lookup table) is a abstract data type composed of a collection of keys and a collection of values, where each key is associated with one value. The relationship between a key and its value is sometimes called a mapping or binding. A valid sample would be a map of capitals of the world’s countries where the country code is the key and the name of the capital is the value, i.e. { { “CH”, “Bern” }, { “D”, “Berlin” }, { “USA”, “Washington” }, …}

A List is collection of objects (also called elements or members). Each element in the List has an index. Similar to a Bag a member of the the list can have more than one membership. A valid sample of a list is e.g. { {1, “Bob”}, {2,”Sue”}, {3,”Ann”}, {4,”Sue”}, …}. Obviously the name “Ann” occurs twice, once with the index 2 and once with the index 4.

.NET and the CLR

The CLR of .NET only provides us Maps and Lists. Maps are either implemented as Hashtables (non generic) or Dictionaries (generic). Lists are available as ArrayList (non generic) or List<T> (generic). But we have no direct representation of Set and Bag in the CLR. A Bag can easily be simulated by using a List. We just have the superfluous index. It is not obvious why Microsoft didn’t implement a Set though. Since NHibernate makes heavy use of sets they provide an implementation of Sets in the so called IESI collection library which is part of the stack.


%d bloggers like this: