简体   繁体   English

LINQ-EF的多个函数参数

[英]Multiple func parameters for LINQ - EF

I was fiddling around with the linq its Func parameter(on entity framework). 我在摆弄linq的Func参数(在实体框架上)。 Then I found out this behaviour 然后我发现了这种行为

var idMatchQuery = new Func<MyClass, bool>(x => x.Id == someId);
var statusMatchQuery = new Func<MyClass, bool>(x => x.Status == someStatus);

/// works
var a = myClassEntity.FirstOrDefault(idMatchQuery);

/// doesn't work
var b = myClassEntity.FirstOrDefault(p => idMatchQuery(p) && statusMatchQuery(p));

/// doesn't work
var c = myClassEntity.FirstOrDefault(p => idMatchQuery(p) && p.Status == 1);

It throws UnsupportedOperationException since the EF does not recognize those queries. 由于EF无法识别这些查询,因此它将引发UnsupportedOperationException I could have accept it much easier if none of the above were not working. 如果以上方法均无效,我本来可以接受的容易得多。 But it bugs me when it works with one and only one Func query, but not with combinations with other queries. 但是,当它仅与一个Func查询一起使用时,却与其他查询结合使用时,却使我感到Func

I'm sure there exist an explanation for it, but I guess my search terms were too naive for the answer I'm looking for. 我敢肯定有一个解释,但是我想我的搜索关键词对于我寻找的答案太幼稚了。

What is the explanation for this behaviour? 这种行为的解释是什么?

It is caused that, EF should translate your predicate to TSQL language. 导致EF将您的谓词转换为TSQL语言。 You can check, that parameter of FirstOrDefault method is not Func<T, bool> , but instead Expression<Func<T, bool>> , because last one give us oppotunity to parse it and translate to TSQL. 您可以检查一下, FirstOrDefault方法的参数不是Func<T, bool> ,而是Expression<Func<T, bool>> ,因为最后一个给了我们解析它并将其转换为TSQL的机会。 When you use two Func<T, bool> or Func<T, bool> with simple condition EF can't translate and parse it to TSQL due to Expression<Func<T, bool>> inner stuff and features complexity, that is why EF keep this predicates at origin state and send to server as it was written at first, as a result - UnsupportedOperationException . 当您使用带有简单条件EF的两个Func<T, bool>Func<T, bool> ,由于Expression<Func<T, bool>>内部内容和功能复杂,EF无法将其转换和解析为TSQL,这就是为什么EF将此谓词保持在原始状态,并按照最初编写的那样发送到服务器,结果是UnsupportedOperationException So, for EF - parse first predicate much more easily than other two. 因此,对于EF-与其他两个谓词相比,解析第一个谓词要容易得多。

Conclusion : it is caused by features and methodology of translation C# predicates from Expression<Func<T,bool>> to TSQL, because of it's sometimes enough high complexity. 结论 :这是由于将C#谓词从Expression<Func<T,bool>>为TSQL的功能和方法所致,因为有时它具有足够高的复杂性。

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

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