【问题标题】:How can I add a LINQ to XML subquery to a LINQ to Entities query?如何将 LINQ to XML 子查询添加到 LINQ to Entities 查询?
【发布时间】:2019-06-13 11:58:13
【问题描述】:

我在 XML 类型的数据库列中有一个 XML 结构,看起来像这样:

<Translation>
   <Language ID="1">
       <Title>Some title</Title>
       <Abbrevation>some abbrevation</Abbrevation>
       <Source>https://www.somesource.com</Source>
   </Language>
   <Language ID="2">
       <Title>some more titles</Title>
       <Abbrevation>some more abbrevation</Abbrevation>
       <Source>https://www.somemoresource.com</Source>
          </Sprache>
</Translation>

现在我需要将此 XML 的元素放入 LINQ to Entities 查询中。 到目前为止我尝试了什么:

return from x in _context.Test
               where((displayAll == false && (x.Aufhebung == null || x.Aufhebung > DateTime.Now)) || (displayAll))
               select new TestViewModel()
               {
                   ID = x.ID,
                   Prop = x.Prop,
                   Number = x.Number ?? "",
                   Title = XElement.Parse(x.Translation).Descendants("Language").Where(f => f.FirstAttribute.Value == "1").Descendants("Title").Single().Value,
               };
    }

模型上的属性是:

public string Translation{ get; set; }

但我总是收到错误消息:

LINQ to Entities 无法识别方法 [System.Xml.Linq.XElement] System.Xml.Linq.XName,并且此方法无法转换为存储表达式。

有没有办法在 LINQ to Entities 中获取 LINQ to XML 子查询?

【问题讨论】:

    标签: c# linq-to-entities linq-to-xml


    【解决方案1】:

    虽然“数据库元素”没有具体化,但在可能的情况下,Linq 方法中的每个表达式都将被转换为 SQL 表达式......但是这个操作:

    Title = XElement.Parse(x.Translation).Descendants("Language").Where(f => f.FirstAttribute.Value == "1").Descendants("Title").Single().Value
    

    正如错误消息文本所说,无法在存储表达式中翻译,这是因为存在 XElement 及其方法。

    要在 Linq 方法中执行此行,您必须具体化由

    返回的 IQueryable
    context.Test.where((displayAll == false && (x.Aufhebung == null || x.Aufhebung > DateTime.Now)) || (displayAll))
    

    然后继续进行该选择。在这种情况下,为了实现这个 IQueryable,在类似于非 SQL 的语法中,Linq 提供 Method .ToList(),在这种情况下将返回一个 List,在应用程序内存上实现并准备好与每个应用程序表达式一起使用.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多