我正在尝试参数化 Entity Framework 查询 (EntityFrameworkCore 1.1.1),但在从“Where”表达式中提取函数时出现错误:
System.NotSupportedException :
Could not parse expression 'school.Programs.Any(__p_0)': The given arguments did not match the expected arguments: Object of type 'System.Linq.Expressions.TypedParameterExpression' cannot be converted to type 'System.Linq.Expressions.LambdaExpression'.
当我尝试调用 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()
}
但是,当我重写 SearchSchools 以便内联 Func
时它工作正常:
// 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()
}
这似乎有点奇怪——我认为他们应该采取同样的行动。为什么会发生这种情况?
最佳答案
第一种情况的错误是你声明了p
作为 Func<Program, bool>
.
它必须是 Expression<Func<Program, bool>>
Entity Framework 理解表达式树。
关于c# - 无法从表达式中提取此函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43057695/