NHibernate 中只读列表的最佳实践是什么 [英] What is the best practice for readonly lists in NHibernate
问题描述
我正在处理的域模型具有根聚合和子实体.类似于以下代码:
Domain Model I am working on has root aggregate and child entities. Something like the following code:
class Order
{
IList<OrderLine> Lines {get;set;}
}
class OrderLine
{
}
现在我想让我的订单控制线路.类似的东西:
Now I want my Order to control lines. Something like that:
class Order
{
OrderLine[] Lines {get;}
void AddLine(OrderLine line);
}
此时我们使用以下模式:
At this time we are using the following pattern:
class Order
{
private IList<OrderLine> lines = new List<OrderLine>();
OrderLine[] Lines {get {return this.lines;}}
void AddLine(OrderLine line)
{
this.orders.Add(line);
{
}
NHibernate 直接映射到 lines 字段.
NHibernate is mapped directly to the lines field.
现在问题...
- 在这种情况下你会练习什么?
- 是否有人使用以下方法:公共 IEnumerable GetLines()
- 您使用什么作为属性的返回类型?可能是 ReadOnlyCollection 或 IEnumerable;
- 这可能不是最好的提问地点吗?请提出建议.
更新:似乎 IEnumerable 获胜,但解决方案仍然不完美...
Update: Seems IEnumerable wins, however solution still is not perfect...
推荐答案
我使用的模式是:
class Order
{
private List<OrderLine> lines = new List<OrderLine>();
IEnumerable<OrderLine> Lines { get { return this.lines; } }
void AddLine(OrderLine line)
{
this.orders.Add(line);
}
}
如果您使用的是 NET 3.5,您可以获得使用 LINQ 的 IEnumerable 所需的所有搜索功能,并且您隐藏了您的集合实现.
If you're using NET 3.5 you get all the search functionality you could want for IEnumerable using LINQ, and you hide your collection implementation.
返回 OrderLine[] 的问题是您的集合可以从外部修改,例如:
The problem with returning OrderLine[] is that your collection can be modified externally eg:
Order.Lines[0] = new OrderLine().
这篇关于NHibernate 中只读列表的最佳实践是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!