Exposing HasMany and ManyToMany relationships as IEnumerable

橙三吉。 提交于 2020-01-02 07:35:53

问题


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:


  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



回答2:


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

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


来源:https://stackoverflow.com/questions/5749356/exposing-hasmany-and-manytomany-relationships-as-ienumerable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!