Skip to main content
 首页 » 编程设计

c#之Entity Framework 5 在过滤结果之前返回整个数据集

2024年02月13日11exmyth

我有一个抽象类,它为我的所有存储库实现 - 在其中我有一个返回集合的属性:

protected readonly IDbSet<T> _dbSet; 
 
public virtual IEnumerable<T> GetSelection(Func<T, bool> where) 
{ 
    return _dbSet.Where(where); 
} 

repo :

public class PostcodeDataRepository : EntityRepositoryBase<PostcodeData>, IPostcodeDataRepository 
{ 
    // Constructor in here 
} 

现在效果很好:

var postcodeData = postcodeRespoistory.GetSelection(x=>x.Postcode == "SW1A 2TT"); 

(是的,这是英国邮政编码数据,是的,表中有将近 200 万行)

这很好用,但我的问题是只为应用程序返回所有数据然后过滤它会导致一些性能问题(如您所料!)。我使用 MiniProfiler 和 EFProf 来确认它正在有效地执行 select * from PostcodeData 这不是我想要的。

有人知道我该如何解决这个问题吗?

请您参考如下方法:

您需要使用 Expression<Func<TSource, bool>>谓词:

public IEnumerable<T> GetSelection(Expression<Func<T, Boolean>> predicate) 
{ 
    return _dbSet.Where(where); 
}