简体   繁体   English

使用Entity Framework进行动态Linq查询

[英]dynamic Linq queries with Entity Framework

I am aware of few efforts in constructing Linq queries dynamically, such as this , and this . 我知道在构建动态LINQ查询一些努力,比如这个这个

None seem to be ideal as I would like to avoid putting expressions in a string, and omitting a where if it is not needed. 似乎没有理想,因为我想避免将表达式放在字符串中,并省略不需要的地方。

My main concern is that the query is optimized for the database, and dynamically omits unnecessary clauses whenever possible. 我主要担心的是查询是针对数据库进行优化的,并且尽可能动态地省略不必要的子句。

Are there any new developments in EF 4.0 for such scenarios? EF 4.0中是否有针对此类场景的新发展?

UPDATE UPDATE

here is one link i found very helpful: http://www.albahari.com/nutshell/predicatebuilder.aspx indeed, adding "And" filters dynamically is trivial, and adding "Or" filters can be done easily using predicate builder: 这里有一个我发现非常有用的链接: http//www.albahari.com/nutshell/predicatebuilder.aspx确实,动态添加“And”过滤器很简单,使用谓词构建器可以轻松添加“Or”过滤器:

var predicate = PredicateBuilder.False<Product>();
predicate = predicate.Or (p => p.Description.Contains (temp));

and according to LinqPad the sql gets emitted accordingly to what filters were applied.. 根据LinqPad,sql会根据应用的过滤器进行相应的调整。

For omitting the Where cause (pseudocode, hope I understood your question correctly): 为了省略Where cause(伪代码,希望我能正确理解你的问题):

var query = IQueryable<Foo>();

if(someCondition)
    query = query.Where(......);

var result = query.Select(.......);

For dynamic queries - I haven't heard about anything new. 对于动态查询 - 我没有听说过任何新内容。 IMHO we will have to stay with strings. 恕我直言,我们将不得不保持弦乐。 Can you come up with some better approach? 你能想出一些更好的方法吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM