Which .Net collection interface to use when in a domain model?
Using the Northwind schema as an example which collection interface would you use in the following circumstances.
(source: techmatica.com) .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 Terri开发者_如何学编程tories but TerritoryId must be unique.
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.
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
精彩评论