存储库是否应该实现 IQueryable<T>? [英] Should repositories implement IQueryable<T>?
问题描述
我正在考虑两个 IRepository 接口之一,一个是 IQueryable 的后代,另一个包含 IQueryable.
I'm considering one of two IRepository interfaces, one that is a descendant of IQueryable and one that contains IQueryable.
像这样:
public interface IRepository<T> : IQueryable<T>
{
T Save(T entity);
void Delete(T entity);
}
或者这个:
public interface IRepository<T>
{
T Save(T entity);
void Delete(T entity);
IQueryable<T> Query();
}
LINQ 用法为:
from dos
in ServiceLocator.Current.GetInstance<IRepository<DomainObject>>()
where dos.Id == id
select dos
或者...
from dos
in ServiceLocator.Current.GetInstance<IRepository<DomainObject>>().Query
where dos.Id == id
select dos
我有点喜欢第一个,但嘲笑它是有问题的.其他人如何实现 LINQable、可模拟的存储库?
I kinda like the first one, but it's problematic to mock. How have other people implemented LINQable, mockable repositories?
推荐答案
取决于你想要 Has-A 还是 Is-A 关系.
Depends on if you want a Has-A or an Is-A relationship.
第一个是 Is-A 关系.IRepository 接口是一个 IQueryable 接口.第二个是has-a.IRepository 有一个 IQueryable 接口.在写这篇文章的过程中,我实际上比第一个更喜欢第二个,因为当使用你的第二个 IRepository 时,我可以给 Query() 方法任何返回 IQueryable 的方法.对我来说,这比第一个实现更灵活.
The first one is an Is-A relationship. The IRepository interface is a IQueryable interface. The second is a has-a. The IRepository has an IQueryable interface. In the process of writing this, I actually like the second better then the first, simply because when use your second IRepository, I can give the Query() method ANYTHING that returns IQueryable. To me, that is more flexible then the first implementation.
这篇关于存储库是否应该实现 IQueryable<T>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!