存储库采用 linq 表达式进行过滤
我正在考虑重构一个存储库,我必须提高其灵活性并减少方法数量。
有以下方法:
Collection GetAllUsersByRole(Role role)
User GetUserByuserName(string userName)
...我想要一个采用 Linq 表达式的方法:
ICollection GetUsers(Expression e)
{
//retrieve user collection from store
//apply expression to collection and return
}
这是一个合理的方法吗?大概我会损失一些效率,因为每次都需要检索和过滤完整的用户集合,而不是根据某些硬编码标准检索用户子集?
编辑:NHibernate 在我的实现中提供了 ORM。
I am considering refactoring a repository I have to improve its flexibility and reduce the method count.
Where there are the following methods:
Collection GetAllUsersByRole(Role role)
User GetUserByuserName(string userName)
...I would like to have a single method taking a Linq expression:
ICollection GetUsers(Expression e)
{
//retrieve user collection from store
//apply expression to collection and return
}
Is this a reasonable approach? Presumably I'd lose some efficiency because the full users collection would need to be retrieved and filtered every time, rather than retrieving a subset of users according to some hard-coded criteria?
Edit: NHibernate provides ORM in my implementation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您确实想将表达式作为该方法的参数。
就性能而言,这实际上取决于您想要走多远。最简单的方法是将所有对象放入内存中,然后用谓词表达式进行过滤。
另一方面,您提到了某种标准。我不知道您的后端数据系统是什么,但您可以采用这些通过的过滤器并将它们转换为您的标准。这本质上就是 Linq to SQL 和 Linq to Entities 所做的事情,但希望您需要支持的可能性范围要小得多。如果没有,如果您想采用这种方法,那么切换到 ORM 工具之一可能是有意义的。
You really want to take an Expression as the argument to that method.
As far as performance, it really comes down to how far you want to go with it. The simplest method is bringing all the objects into memory and then filtering with the predicate expression.
On the other hand, you mention some sort of criteria. I have no idea what your back end data system is, but you can take these passed filters and transform them into your criteria. This is essentially what Linq to SQL and Linq to Entities does, but hopefully the range of possibilities you need to support is significantly smaller. If not, it might make sense to switch to one of the ORM tools if you want to take this approach.
这不是一个非常合理的方法,因为通常会给您带来很多性能问题。如果您使用接受 LINQ 查询的数据访问技术,那么您就可以使用此查询(表达式)。对于 LINQ to SQL,这可以是 IQueryable,对于 EntityFramework,可以是 ObjectQuery。它也可以是 nHibernate 的ICriteria(没有 linq 支持)。所有现代 ORM 工具都有自己的表达式 API,因此您只需要使用它即可。如果您有自定义数据访问层,则需要编写自己的 API 来创建条件,例如 查询对象< /a>.
This is not a very reasonable approach, cos typically will cost you a lot of performance issues. If you use data access technology that accepts LINQ queries than you just can use this query (expression) with it. This can be IQueryable for LINQ to SQL or ObjectQuery for EntityFramework. It also can be ICriteria (without linq support) for nHibernate. All modern ORM tools have its own expression API, so you just need to use it. If you have custom Data Access layer you will need to write your own API for creating criterias, for example Query Object.