简体   繁体   English

将谓词传递给LINQ where子句

[英]Passing predicate to LINQ where clause

Hey I have following code: 嘿,我有以下代码:

    Func<Assoc, bool> predicate = (x) => 
    (
        !String.IsNullOrWhiteSpace(version) ? x.Version.Contains(version) : x.Version != null

    );

    var assocs = _context.Assoc
                    .Where(x => x.Model == model)
                    .Where(predicate)
                    ;

But it doesn't work. 但这是行不通的。 If I try to execute this server gives me Internal Server Exception but if I change this to 如果我尝试执行此服务器,则会出现内部服务器异常,但如果我将其更改为

var assocs = _context.Assoc
      .Where(x => x.Model == model)
      .Where(x => x.Version.Contains(version))
;

it works as I expect. 它按我的预期工作。

Why is that? 这是为什么?

Is it possible to get preview of Linq generated query? 是否可以预览Linq生成的查询?

Using LINQKit you can create predicates that will be expanded for you so you can use them in IQueryable expressions, but you don't need that for just excluding version testing. 使用LINQKit,您可以创建将为您扩展的谓词,以便可以在IQueryable表达式中使用它们,但是您不需要仅用于版本测试的谓词。

var assocs = _context.Assoc
             .Where(x => x.Model == model);
if (!String.IsNullOrWhiteSpace(version))
    assocs = assocs.Where(x.Version.Contains(version));

becuse the EF can translate Contains method to sql ( Version LIKE '%@version%' ), but no evaluate your "external" function. 因为EF可以将Contains方法转换为sql( Version LIKE '%@version%' ),但是无法评估您的“外部”函数。

if you load the result to memroy (by export method as ToList() ) you can do it as linq2object: 如果将结果加载到内存中(通过导出方法为ToList() ),则可以将其作为linq2object进行操作:

var assocs = _context.Assoc.ToList()
                .Where(x => x.Model == model)
                .Where(predicate);

My code shows and illustrates but it is definitely not recommended, because it is better to question the DB than to work on memory. 我的代码可以显示和说明,但是绝对不建议这样做,因为对数据库的质疑比在内存上的工作要好。

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

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