0

我有错误 LINQ to Entities 不支持 LINQ 表达式节点类型“调用”。

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));

我哪里写错了?

4

2 回答 2

3

LINQ to SQL 和 LINQ to Entities 都在 上工作Expression,而不是在Func(就像 LINQ to Objects 一样),所以你必须声明你的userIsAdminas 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));

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

于 2013-09-23T12:03:52.933 回答
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();
于 2015-05-07T08:10:00.677 回答