开发者

Exposing HasMany and ManyToMany relationships as IEnumerable

Currently in my entities I'm exposing my collections as an IList but I've been thinking about exposing them as a IEnumerable to prevent users from manually adding to the collections. I have specific adds for these operations so that I can make sure my bi-directional relationships stay intact. A couple questions come to mind in this scenario.

  1. If I expose them as IEnumberable does this mean I'll need an Add and开发者_开发知识库 Remove method for every collection that represents a relationship in my entities?
  2. Is there an easier way to do this? I'm not against doing it this way just wondering.
  3. Are you doing it this way?

Example:

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
}

Converting the class above so that we only expose IEnumerable would result in:

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);
    }
}


  1. Yes, if you expose an IEnumerable it is best to add methods on the class to handle Add/Remove
  2. A private backing field is a pretty good solution.
  3. Yes, but keep in mind if you want truly read only access to the exposed collection use ReadOnlyCollection - http://msdn.microsoft.com/en-us/library/ms132474.aspx


Agreed with Dan's answer, with a minor change:

public IEnumerable<OrderLine> OrderLines
{ get { return orderLines.Select(x => x; } }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜