Tolga Evcimen
Tolga Evcimen

Reputation: 7352

Multiple func parameters for LINQ - EF

I was fiddling around with the linq its Func parameter(on entity framework). 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. 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.

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?

Upvotes: 2

Views: 280

Answers (1)

Slava Utesinov
Slava Utesinov

Reputation: 13488

It is caused that, EF should translate your predicate to TSQL language. 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. 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. So, for EF - parse first predicate much more easily than other two.

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.

Upvotes: 4

Related Questions