在域模型中使用哪个 .Net 集合接口?
以 Northwind 模式为例,在以下情况下您将使用哪个集合接口。
(来源:techmatica.com)
。
客户
客户有一个订单集合。就本示例而言,Orders 集合是只读的。
订单
订单具有订单详细信息的集合。可以将 OrderDetail 添加到集合中。
员工
员工拥有一系列区域。一个 Employee 可以属于 0 个或多个 Territories,但 TerritoryId 必须是唯一的。
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 Territories but TerritoryId must be unique.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
ICollection
在订单和订单详细信息的所有三种情况下。只读集合没有特定的接口,这是由实现处理的(在这种情况下,您可以使用ReadOnlyCollection
作为具体类型)。您还可以使用IList
,但它仅添加对按索引访问的支持,这在关系模型中通常没有任何意义。对于地区,您可以使用
ISet
(假设您使用的是.NET 4.0)。实现此接口的类不允许重复的项目。Use
ICollection<T>
in all three casesfor Orders and OrderDetails. There is no specific interface for readonly collections, this is handled by the implementation (you could use aReadOnlyCollection<T>
as the concrete type in that case). You could also useIList<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.需要更多信息。例如,为什么 Orders 集合是只读的?这些集合要如何使用?这里有很多变数。
关键是,将它们公开为满足您需求的最简单的界面。如果您总是简单地迭代整个列表而不向其中添加内容,请不要使用
ICollection
。另一方面,如果您发现自己想要转换为IList
以按索引添加或获取项目,请不要使用IEnumerable
。例如,如果您创建了一个通过 MVVM 进行演示的模型,我可能建议您使用
BindingList
。如果您只对订单进行求和操作,我可能会建议使用简单的IEnumerable
。 ETCNeeds 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 anIEnumerable<T>
if you find yourself wanting to cast to anIList<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 simpleIEnumerable<T>
. Etc