Can't retrieve this function from expression
I am trying to parameterize an Entity Framework (EntityFrameworkCore 1.1.1) query, but I am getting an error when retrieving the function from the "Where" expression:
System.NotSupportedException:
Unable to parse expression "school.Programs.Any (__ p_0)": given arguments did not match expected arguments: Object type "System.Linq.Expressions.TypedParameterExpression" could not be converted to type "System.Linq. Expressions.LambdaExpression".
I am getting this error when I try to call SearchSchools()
:
public IQueryable<SchoolResult> SearchSchoolQueryable(
Expression<Func<School, bool>> schoolExpression)
{
return _dbContext.School
.Where(schoolExpression)
.Select(s => new SchoolResult
{
Id = s.Id,
Name = s.Name
}
);
}
// hardcoded test: doesn't work
public async Task<IEnumerable<SchoolResult>> SearchSchools()
{
Func<Program, bool> p = program => program.Name.StartsWith("U");
Expression<Func<School, bool>> expr = school => school.Active
&& school.Programs.Any(p);
return await SearchSchoolQueryable(expr)
.ToListAsync()
}
However, it works great when I rewrite SearchSchools to Func
be nested:
// hardcoded test: works ok
public async Task<IEnumerable<SchoolResult>> SearchSchools()
{
Expression<Func<School, bool>> expr = school => school.Active
&& school.Programs.Any(program => program.Name.StartsWith("U"));
return await SearchSchoolQueryable(expr)
.ToListAsync()
}
It seems strange - I thought they should act the same way. Why might this happen?
source to share
The second example works because you have Expression
one that represents the creation Func<Program, bool>
. You must have Func<Program, bool>
because expected Any
, but all the details of this Func
must be in Expression
so that the request provider can see all of this information and process it.
Your first example Func<Program, bool>
is generated in code, not in Expression
, so it's just plain old compiled code, and the query provider doesn't have enough information to translate some arbitrary .NET code into SQL, so all it can do is raise its hands ...
source to share