将 HasMany 和 ManyToMany 关系公开为 IEnumerable
目前,在我的实体中,我将集合公开为 IList,但我一直在考虑将它们公开为 IEnumerable,以防止用户手动添加到集合中。我为这些操作添加了特定的内容,以便我可以确保我的双向关系保持完整。在这种情况下,我想到了几个问题。
- 如果我将它们公开为 IEnumberable 是否意味着我需要为每个代表实体中关系的集合提供一个 Add 和 Remove 方法?
- 有没有更简单的方法来做到这一点?我并不反对这样做,只是想知道。
- 你这样做吗?
示例:
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);
}
}
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
同意 Dan 的回答,稍作修改:
Agreed with Dan's answer, with a minor change: