如何将谓词正确传递给包含的导航属性的"where"方法?



我需要构造"其中";linq查询的included属性的谓词取决于条件。为了达到这个目的,我使用了表达式,结果得到了Func<in T, out TResult>类型的谓词。但是,当我试图将谓词传递给包含属性的.Where()方法时,我得到了异常:

var result = query
.Include(x => x.Collection.Where(predicate))
.ToList();

例外:

Expression of type 'System.Func`2[...]' cannot be used for parameter of type 'System.Linq.Expressions.Expression`1[System.Func`2[...]]' of method 'System.Linq.IQueryable`1[...] Where[...](System.Linq.IQueryable`1[...], System.Linq.Expressions.Expression`1[System.Func`2[...]])' (Parameter 'arg1')

但是直接传递等价于谓词的lambda不会引起任何问题:

var result = query
.Include(x => x.Collection.Where(c => someCondition1(c) && someCondition2(c)))
.ToList();

Linq需要能够将谓词表达式拆开,并从中创建SQL语句。因此

Func<Item, bool> predicate = (c => someCondition1(c) && someCondition2(c);

它需要:

Expression<Func<Item, bool>> predicate = (c => someCondition1(c) && someCondition2(c);

最新更新