动态表达式树如何
使用多种方法实现了通用存储库。其中之一是:
public IEnumerable<T> Find(Expression<Func<T, bool>> where)
{
return _objectSet.Where(where);
}
给定
为
,很容易这样称呼它:
Expression<Func<Culture, bool>> whereClause = c => c.CultureId > 4 ;
return cultureRepository.Find(whereClause).AsQueryable();
但现在我看到(意识到)这种查询的目的是“仅限制一个条件”。 我想做的是:
在上面的例子中,c 是文化类型。文化有几个属性,例如 CultureId、Name、Displayname... 我该如何表达以下内容: 文化ID> 4 和 Name.contains('de') 并在另一个执行中 Name.contains('us') 和 Displayname.contains('ca') 和 ....
这些查询应该动态创建。 我查看了表达式树(因为我认为这是解决我的问题的方法 - 顺便说一句,我以前从未使用过它们),但我找不到任何符合我要求的内容。
这如何构建?
提前致谢
Implemented a generic repository with several Methods. One of those is this:
public IEnumerable<T> Find(Expression<Func<T, bool>> where)
{
return _objectSet.Where(where);
}
Given <T>
to be <Culture>
it is easy to call this like this:
Expression<Func<Culture, bool>> whereClause = c => c.CultureId > 4 ;
return cultureRepository.Find(whereClause).AsQueryable();
But now i see (realize) that this kind of quering is "limiting only to one criteria".
What i would like to do is this:
in the above example c is of type Culture. Culture has several properties like CultureId, Name, Displayname,...
How would i express the following:
CultureId > 4 and Name.contains('de') and in another execution
Name.contains('us') and Displayname.contains('ca') and ....
Those queries should be created dynamically.
I had a look in Expression trees (as i thought this to be a solution to my problem - btw i never used them before) but i cannot find anything which points to my requirement.
How can this be costructed?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要做任何特别的事情,以下内容就可以工作:
You don't need to do anything special, the following will work:
关于对一个参数的限制,Codeka 给了我一个重新思考我的陈述的提示。
事实证明,使用我们想要查询的所有具有值的属性来实现场景非常容易。例如,如果 Cutlure 类型定义有 3 个属性
Name string
Displayname string
CultureId int
,则可以实现这样的 Filter-Expression
正如您所见,我正在使用 &&每个属性之间的运算符来缩小结果(可以使用 || 来扩大结果 - 从而实现 OR)。
再次感谢codeka!
Codeka gave me a hint for re-thinking my statement, regarding this limitation to one parameter.
Turns out it very easy to implement a scenario with all the properties we want to query, which have values. For example if the Cutlure type is defined with 3 properties
Name string
Displayname string
CultureId int
than one can implement a Filter-Expression like this
As you can see i 'm using the && operator between each property to narrow the results (one could use the || to widen the results - thus implementing OR).
Thank you again codeka !