【发布时间】:2013-01-10 10:28:12
【问题描述】:
我有一个具有如下集合属性的实体:
public class MyEntity
{
public virtual ICollection<OtherEntity> Others { get; set; }
}
当我通过数据上下文或存储库检索此实体时,我想防止其他人通过使用MyEntity.Others.Add(entity) 将项目添加到此集合中。这是因为我可能希望在将我的实体添加到集合之前执行一些验证代码。我会通过在MyEntity 上提供这样的方法来做到这一点:
public void AddOther(OtherEntity other)
{
// perform validation code here
this.Others.Add(other);
}
到目前为止,我已经测试了一些东西,我最终得出的结果是这样的。我在我的实体上创建了一个private 集合并公开了一个public ReadOnlyCollection<T>,所以MyEntity 看起来像这样:
public class MyEntity
{
private readonly ICollection<OtherEntity> _others = new Collection<OtherEntity>();
public virtual IEnumerable<OtherEntity>
{
get
{
return _others.AsEnumerable();
}
}
}
这似乎正是我正在寻找的,我的单元测试通过了,但我还没有开始做任何集成测试,所以我想知道:
- 有没有更好的方法来实现我的目标?
- 如果我决定走这条路(如果可行),我将面临哪些影响?
始终感谢您的任何帮助。
编辑 1 我已从使用 ReadOnlyCollection 更改为 IEnumerable 并使用 return _others.AsEnumerable(); 作为我的吸气剂。单元测试再次顺利通过,但我不确定在集成过程中会遇到哪些问题,EF 开始使用相关实体构建这些集合。
编辑 2 所以,我决定尝试创建派生集合(称为 ValidatableCollection)的建议,实现 ICollection,其中我的 .Add() 方法将对之前提供的实体执行验证将其添加到内部集合中。不幸的是,Entity Framework 在构建导航属性时调用了这个方法——所以它并不适合。
【问题讨论】:
-
你使用什么 .net 版本?
-
@IlyaIvanov 我的项目是 MVC3,所以我使用的是 .NET 4.0。
标签: c# entity-framework validation collections