【发布时间】:2015-08-16 04:52:42
【问题描述】:
我使用 EntityFramewotk 和代码优先方法。所以,我这样描述我的模型:
class Person
{
public long Id { get;set; }
public string Name { get;set; }
public ICollection<Person> Parents { get;set; }
}
但是,我的域逻辑不允许修改父母集合(添加、删除),它必须是只读的(仅作为示例)。 EntityFramework 要求所有 Collections 都有ICollection<T> 接口,它有Add 方法(实现结果)和Remove 方法等。
我可以通过显式实现接口来创建自己的集合:
public class ParentsCollection : ICollection<Person>
{
private readonly HashSet<Person> _collection = new HashSet<Person>();
void ICollection<Person>.Add(Person item)
{
_collection.Add(item);
}
bool ICollection<Person>.Remove(Person item)
{
return _collection.Remove(item);
}
//...and others
}
这隐藏了Add 和Remove 方法,但根本不保护。因为我总是可以转换为 ICollection 并调用禁止的方法。
所以,我的问题是:
- 有没有办法在 EntityFramework 中使用只读集合?
【问题讨论】:
标签: c# entity-framework