目前在我的实体中,我将我的集合公开为IList,但我一直在考虑将它们公开为IEnumerable以防止用户手动添加到集合中。我为这些操作添加了特定的内容,以便确保我的双向关系保持不变。在这种情况下会想到几个问题。
示例:
public class OrderHeader
{
public virtual Guid OrderId { get; private set; }
public virtual IList<OrderLine> OrderLines { get; set; }
public virtual void AddLine(OrderLine orderLine)
{
orderLine.Order = this;
OrderLines.Add(orderLine);
}
//No need for a remove method since we expose collection as IList
}
转换上面的类以便我们只公开IEnumerable会导致:
public class OrderHeader
{
public virtual Guid OrderId { get; private set; }
private IList<OrderLine> orderLines { get; set; }
public IEnumerable<OrderLine> OrderLines { get { return orderLines; } }
public virtual void AddLine(OrderLine orderLine)
{
orderLine.Order = this;
orderLines.Add(orderLine);
}
public virtual void RemoveLine(OrderLine orderLine)
{
orderLines.Remove(orderLine);
}
}
答案 0 :(得分:2)
答案 1 :(得分:2)
同意Dan的回答,稍作改动:
public IEnumerable<OrderLine> OrderLines
{ get { return orderLines.Select(x => x; } }