LINQ表达式节点类型' Invoke' LINQ to Entities中不支持skip

时间:2013-09-23 11:57:50

标签: c# linq

我有错误LINQ to Entities不支持LINQ表达式节点类型'Invoke'。

var result = context.Users.Include("Roles")
                          .OrderBy(x => x.UserID)
                          .Where(x => !userIsAdmin(x))
                          .Skip(skip)
                          .Take(take)
                          .ToList();

private readonly Func<User, bool> userIsAdmin = u => u.Roles.Any(y => y.Name.Equals(AdminRoleName));

我写错的地方?

2 个答案:

答案 0 :(得分:3)

LINQ to SQL和LINQ to Entities都可以在Expression上工作,而不是Func(就像LINQ to Objects那样),所以你必须将userIsAdmin声明为Expression<Func<User, bool>> }:

private readonly Expression<Func<User, bool>> userIsAdmin = u => u.Roles.Any(y => y.Name.Equals(AdminRoleName));

您还应该考虑将表达式更改为:

private readonly Expression<Func<User, bool>> userIsAdmin = u => u.Roles.Select(y => y.Name).Contains(AdminRoleName));

应该在生成的SQL查询中将其翻译为IN语句。

答案 1 :(得分:0)

MarcinJuraszek走在正确的轨道上。您可以将谓词更改为:

private readonly Expression<Func<User, bool>> userIsNotAdmin = u => !u.Roles.Any(y => y.Name.Equals(AdminRoleName));

请注意,这是您所拥有的内容的反转。

然后你应该可以这样称呼它:

var result = context.Users.Include("Roles")
                      .OrderBy(x => x.UserID)
                      .Where(userIsNotAdmin)
                      .Skip(skip)
                      .Take(take)
                      .ToList();