LINQ Expression Tree Any() inside Where()

偶尔善良 提交于 2019-12-04 04:36:15

Please note: Everything after and including ToList() won't work on IQueryable<T> but on IEnumerable<T>. Because of this, there is no need to create expression trees. It certainly is nothing that is interpreted by EF or similar.

If you would look at the code that is generated by the compiler for your original query, you would see that it generates expression trees only until just before the first call to ToList.

Example:

The following code:

var query = new List<int>().AsQueryable();
query.Where(x => x > 0).ToList().FirstOrDefault(x => x > 10);

Is translated by the compiler to this:

IQueryable<int> query = new List<int>().AsQueryable<int>();
IQueryable<int> arg_4D_0 = query;
ParameterExpression parameterExpression = Expression.Parameter(typeof(int), "x");
arg_4D_0.Where(Expression.Lambda<Func<int, bool>>(Expression.GreaterThan(parameterExpression, Expression.Constant(0, typeof(int))), new ParameterExpression[]
{
    parameterExpression
})).ToList<int>().FirstOrDefault((int x) => x > 10);

Please note how it generates expressions for everything up to ToList. Everything after and including it are simply normal calls to extension methods.

If you don't mimick this in your code, you will actually send a call to Enumerable.ToList to the LINQ provider - which it then tries to convert to SQL and fail.

It looks like, when constructing whereLambda, your second parameter should be subscribersParameter and not subscriptionParameter. At least, that would be the cause of your exception.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!