【发布时间】:2014-06-07 06:23:35
【问题描述】:
我有标准的存储库接口设置:
public interface IRepository<T, TKey> : IDisposable where T : class
{
T Get(TKey id);
IEnumerable<T> Get();
IEnumerable<T> Find(Expression<Func<T, bool>> whereClause);
T Add(T entity);
void Delete(T entity);
bool Save();
int Update(T entity);
}
并且有一个实现:
public class EfRepository<T, TKey> : IRepository<T, TKey> where T : class
{
protected DbContext _context;
public EfRepository(DbContext context) { ...}
public virtual T Get(TKey id) {...}
public virtual IEnumerable<T> Get() { ...}
public virtual IEnumerable<T> Find(Expression<Func<T, bool>> whereClause) { ...}
public T Add(T entity) { ...}
public void Delete(T entity) { ...}
public bool Save() { ...}
public int Update(T entity) { ...}
}
在这之上还有一个服务层:
public class VehicleService: IVehicleService
{
private readonly IRepository<Vehicle, int> _repository;
public VehicleService(IRepository<Vehicle, int> repository)
{
_repository = repository;
}
public IEnumerable<int> GetModelYears()
{
// ?? help?
}
}
我的问题是,在哪里实现 Distinct 方法? LINQ 查询如下所示:
context.Set<Vehicle>().Select(x => x.ModelYear).Distinct();
我还没有弄清楚如何在存储库级别对 Distinct 方法进行通用编码,而且我认为这不是放置它的正确位置。
我们已选择不在我们的存储库中返回 IQueryable。但我也没有向服务层公开任何实际的 DbSet 对象。
也许更好的问题是,这是一种正确的做事方式吗?有没有更好的办法?
【问题讨论】:
-
废话,有 2 个用户给出了我要回答的问题,但我如何确定让谁成为“已接受”?我让他们争吵吗?
-
这一切都取决于你,伙计;)
-
接受了 thsoren 的回答,因为它更详细。但也赞成 user902553 的回答,因为它基本上是同一件事并提供选项/解释。谢谢你们。
标签: c# entity-framework repository distinct