问题
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.
- 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?
- Is there an easier way to do this? I'm not against doing it this way just wondering.
- 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
- A private backing field is a pretty good solution.
- 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