I would only use stored procedure if you really want to optimize your sql. Otherwise if you want to keep it flexible and make it possible to plugin filters easily I would recommend a type pipes and filters pattern. It would work like this:
public class ProductRepository
{
public IQueryable<Prodcut> GetAll()
{
return yourContext.Products;
}
}
public static class ProductFilters
{
public static IQueryable<Product> ByCategory(this IQueryable<Product> query, string category)
{
return query.Where(p => p.Category == category);
}
}
The name ProductRepository is probably wrong in this case since it is not truly a repository, more some kind of "bridge". But this pattern allow you to easily add additional filters like extension methods. It is important that you return IQueryable from the extension methods and your "repository", this make the query to be evaluated only once and you can chain your filters.
发布评论
评论(2)
如果你真的想优化你的sql,我只会使用存储过程。否则,如果您想保持灵活性并使其可以轻松插入过滤器,我会推荐类型管道和过滤器模式。它的工作方式如下:
在这种情况下,名称
ProductRepository
可能是错误的,因为它不是真正的存储库,更多的是某种“桥梁”。但这种模式允许您轻松添加其他过滤器,例如扩展方法。从扩展方法和“存储库”返回IQueryable
非常重要,这使得查询仅被评估一次,并且您可以链接过滤器。I would only use stored procedure if you really want to optimize your sql. Otherwise if you want to keep it flexible and make it possible to plugin filters easily I would recommend a type pipes and filters pattern. It would work like this:
The name
ProductRepository
is probably wrong in this case since it is not truly a repository, more some kind of "bridge". But this pattern allow you to easily add additional filters like extension methods. It is important that you returnIQueryable
from the extension methods and your "repository", this make the query to be evaluated only once and you can chain your filters.我在类似情况下使用以下内容:
I am using the following in similar cases: