views:

62

answers:

2

Using the Northwind schema as an example which collection interface would you use in the following circumstances.

Northwind Schema.

Customer

Customer has a collection of Orders. For the purpose of this example the Orders collection is readonly.

Order

An Order has collection of OrderDetails. An OrderDetail can be added to the collection.

Employee

An Employee has collection of Territories. An Employee can belong to 0 or more Territories but TerritoryId must be unique.

+2  A: 

Use ICollection<T> in all three cases for Orders and OrderDetails. There is no specific interface for readonly collections, this is handled by the implementation (you could use a ReadOnlyCollection<T> as the concrete type in that case). You could also use IList<T>, but it only adds support for access by index, which usually doesn't really make sense in a relational model.

For Territories, you could use ISet<T> (assuming you're using .NET 4.0). Classes that implement this interface don't allow duplicate items.

Thomas Levesque
The safest read only collection is IEnumerable<T>, as ICollection supports Add()
Alex Lo
Yes, I guess IEnumerable<T> would be OK too. But it doesn't really prevent modification of the collection: if the actual collection is an ICollection<T>, you can still cast to ICollection<T> and then call Add...
Thomas Levesque
ICollection<T> interface does not stipulate that items must be unique. Therefore does it not break the requirements for Customer.Territories?
Tim Murphy
I missed that requirement when reading your question, see my updated answer
Thomas Levesque
+1  A: 

Needs a bit more info. For example, why is Orders collection read-only? How are these collections to be used? There are many variables here.

The key is, expose them as the most simple interface that meets your needs. Don't use an ICollection<T> if you always simply iterate over the list as a whole and never add to it. On the other hand, don't use an IEnumerable<T> if you find yourself wanting to cast to an IList<T> to add or get items by index.

For example, if you are created a model for presentation via MVVM, I may suggest that you use a BindingList. If you only do summing operations on orders, I may suggest a simple IEnumerable<T>. Etc

Philip Rieck