【问题标题】:Getting error when using a List in a where clause in Entity Framework在实体框架的 where 子句中使用列表时出错
【发布时间】:2015-11-16 14:47:33
【问题描述】:

最近看了下面的帖子Using a List in a where clause in Entity Framework

我已经尝试过这样做。在示例中,我们有以下代码作为 example

List<int> docIds = (from d in doc
                      where d.Tags.All(t => _tags.Contains(t))
                      select d.id).ToList<int>();

在这里,我们有我的代码:

List<PostOrcamentoServico> lOrcamentos = (from orcamento in db.PostOrcamentoServico
                                         where orcamento.Servicos.All(s => usuario.Clientes.Servicos.Contains(s))
                                        select orcamento).ToList();

但是,我总是收到此错误:

Unable to create a constant value of type 'Servicili.Models.Servicos'. Only primitive types or enumeration types are supported in this context.

我已经尝试过 lamda、LINQ 等。但是,没有任何效果。

这个想法如下:PostOrcamentoServico 就像一个预算,其中必须有一种或多种服务。 另一方面,用户登录,注册指定他可以提供的所有专业服务。因此,当他试图搜索预算时,他只能搜索用户(专业)提供的服务的预算。

  1. 预算 -> 一对多服务;
  2. 2.Professioanl -> 一对多服务;
  3. 搜索 = 专业服务列表中包含服务的所有预算。

【问题讨论】:

    标签: c# linq entity-framework list lambda


    【解决方案1】:

    如果Servicili.Models.Servicos 类有唯一标识符,那么试试这个:

    var servicios=usuario.Clientes.Servicos.Select(s=>s.Id);
    List<PostOrcamentoServico> lOrcamentos = (from orcamento in db.PostOrcamentoServico
                                              where orcamento.Servicos.All(s => servicios.Contains(s.Id))
                                              select orcamento).ToList();
    

    正如例外所说,您不能将Contains 方法用于非原始值。仅支持原始类型或枚举类型,因为它们可以转换为 SQL。这就是您需要将服务列表 (usuario.Clientes.Servicos) 转换为原始类型集合的方式,您可以在其中识别所有要使用的服务比较。如果Servicos 类是您模型的实体,您应该有一个Id 属性:

    var servicios=usuario.Clientes.Servicos.Select(s=>s.Id);
    

    【讨论】:

    • Servicos 是服务列表。
    • 感谢您的解释。我看错了,你写的是解决这个问题的正确方法。
    【解决方案2】:

    错误描述非常准确:您在该 Contains 语句中使用了非原始类型。原始类型集合是必需的,因为实体框架知道如何将它们转换为 sql 查询,如下所示:

    Select Name from Persons where City in ('Berlin', 'Paris', 'Rome');
    

    现在想象一下将非原始collection.Contains() 转换为类似上述的sql 查询。

    解决方案是构建一个 ID 列表,然后使用该列表。包含在您的其他查询中,但当然,给它一个 id 参数。

    编辑:就像 octavio 在他的回答中所说的那样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-31
      • 2019-10-13
      • 2010-11-08
      • 2011-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多