在 Linq to Entities 中将 func 作为参数传递和“内部 .NET Framework 数据提供程序错误 1025”错误
我们有一个名为 Task 的类:
public partial class Task : EntityObject
{
public EntityCollection<TaskUser> TaskUsers { get {...} set{...} }
}
它具有名为 TaskUsers 的导航属性,其中包含附加到此任务的用户:
public partial class TaskUser : EntityObject
{
public User User { get {...} set { } }
}
每个 TaskUser 对象都有 User 对象。
我们得到了 IQueryable
tasks.Where(t => t.TaskUsers.Any(a => a.User.ID == 1))
一切正常。当我们使用时,
Func<TaskUser, bool> function = a => a.User.ID == 1;
return tasks.Where(t => t.TaskUsers.Any(function));
我们会得到很好的'Internal .NET Framework Data Provider error 1025'
错误。为什么?我想使用 Expression
类构建更复杂的过滤器,但如果我无法传递简单的 Func
,则无法完成此操作。我应该怎么办?
编辑
也许
Func<TaskUser, bool> function = a => a.User.ID == 1;
return tasks.Where(t => t.TaskUsers.Any(function));
不起作用,但
Expression<Func<TaskUser, bool>> expression = a => a.User.ID == 1;
return tasks.Where(t => t.TaskUsers.AsQueryable().Any(expression));
可以!这就是我所需要的。
We have a class called Task:
public partial class Task : EntityObject
{
public EntityCollection<TaskUser> TaskUsers { get {...} set{...} }
}
It has navigation property called TaskUsers, which contains users attached to this taks:
public partial class TaskUser : EntityObject
{
public User User { get {...} set { } }
}
Every TaskUser object has User object.
We are given IQueryable<Task> tasks
. We want to find tasks assigned to user with ID = 1. When we use
tasks.Where(t => t.TaskUsers.Any(a => a.User.ID == 1))
everything works fine. When we use
Func<TaskUser, bool> function = a => a.User.ID == 1;
return tasks.Where(t => t.TaskUsers.Any(function));
we get nice 'Internal .NET Framework Data Provider error 1025'
error. Why? I want to build much more complicated filters using Expression
class, but if I can't pass simple Func
, this can't be done. What should I do?
EDIT
Maybe
Func<TaskUser, bool> function = a => a.User.ID == 1;
return tasks.Where(t => t.TaskUsers.Any(function));
doesn't work, but
Expression<Func<TaskUser, bool>> expression = a => a.User.ID == 1;
return tasks.Where(t => t.TaskUsers.AsQueryable().Any(expression));
works! That is all I needed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
那么 EF 只能转换表达式,不能转换函数。
即它可以翻译这个:
但不能翻译这个:
至于如何合并表达式(以伪代码):
可能有一些表达式专家可以提供帮助。
我建议针对该特定问题提出一个后续问题
Alex
Well the EF can only translate Expressions, not functions.
i.e. it can translate this:
but not this:
As for how to merge expressions (in pseudo code):
There are probably some Expression guru's who can help with that.
I suggest a followup question focused on that particular problem
Alex