Linq:查询语法,其中运算符不理解表达式类型的谓词

发布于 2024-12-14 05:55:37 字数 717 浏览 5 评论 0 原文

我已将规范定义为 Expression> 类型的对象,如下所示:

public static Expression<Func<User, bool>> IsSystemUser
{
  get
  {
    return user => user.UserID == -1;
  }
}

这对于以扩展方法语法编写的查询效果非常好:

return workspace.GetDataSource<User>().Where(UserSpecifications.IsSystemUser);

但不适用于 Linq 查询语法:

return from user in workspace.GetDataSource<User>() where UserSpecifications.IsSystemUser select user;

编译器给我 cannot 隐式转换类型 'Expression>'为“布尔”。

什么给?我认为 Linq 查询语法只是一个可爱的 DSL,装饰了扩展方法语法。谁能告诉我如何将我可爱的规范与 Linq 查询语法结合使用?

I have defined a specification as an object of type Expression<Func<User, bool>> like this:

public static Expression<Func<User, bool>> IsSystemUser
{
  get
  {
    return user => user.UserID == -1;
  }
}

This works marvellously with queries written in extension method syntax:

return workspace.GetDataSource<User>().Where(UserSpecifications.IsSystemUser);

But not with Linq query syntax:

return from user in workspace.GetDataSource<User>() where UserSpecifications.IsSystemUser select user;

The compiler gives me cannot implicitly convert type 'Expression<Func<User, bool>>' to 'bool'.

What gives? I thought Linq query syntax was just a cute DSL dressing up the extension method syntax. Can anyone tell me how I might use my lovely specifications with Linq query syntax?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦里兽 2024-12-21 05:55:37

您的查询表达式将被转换为:

return workspace.GetDataSource<User>()
                .Where(user => UserSpecifications.IsSystemUser);

lambda 表达式是隐式引入的 - 但在这种情况下您不需要它。所以不要使用查询表达式语法...鉴于这里的查询表达式语法比直接使用扩展方法更长,并且引入了更多的麻烦,你为什么需要它?

请注意,您可以像这样混合搭配:

return from user in workspace.GetDataSource<User>()
                             .Where(UserSpecifications.IsSystemUser)
       where user.Name == "Bob"
       orderby user.ID
       select user;

Your query expression is being translated into:

return workspace.GetDataSource<User>()
                .Where(user => UserSpecifications.IsSystemUser);

The lambda expression is introduced implicitly - but you don't want it in this case. So don't use query expression syntax... Given that here the query expression syntax is longer than using the extension methods directly, and introduces more cruft, why would you want it?

Note that you can mix and match like this:

return from user in workspace.GetDataSource<User>()
                             .Where(UserSpecifications.IsSystemUser)
       where user.Name == "Bob"
       orderby user.ID
       select user;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文