【问题标题】:Querying SQL table with LINQ and XElement使用 LINQ 和 XElement 查询 SQL 表
【发布时间】:2019-03-09 17:58:28
【问题描述】:

我不知道这是否可行,但我想从 SQL 表中检索一些字段以及表中 XML 字段中的特定值,例如

MyTable(UserName varchar(50),XML_Response XML)

注意:C#中字段XML_Response的值的数据类型是XElement

下面的XML_Response 字段内的XML 可以有两种形式 | 没有标签内的值更新结果描述:

<IntegrationResults>
  <UpdateResult>Failure</UpdateResult>
  <UpdateResultDescription>LeadId 2876474 not found</UpdateResultDescription>
</IntegrationResults>
<IntegrationResults>
    <UpdateResult>Success</UpdateResult>
    <UpdateResultDescription />
</IntegrationResults>

我的查询输出我希望看起来像这样(以 2 行为例)

"My User Name","LeadId 83608 not found"
"My User Name 2",""

提前谢谢你

【问题讨论】:

    标签: c# sql-server linq linq-to-sql linq-to-xml


    【解决方案1】:

    作为您尝试的替代方法,您可以使用 C# 命令对象并直接在表上运行以下 SQL:

    SELECT UserName
          , IntegrationResults.n.value('UpdateResultDescription[1]','VARCHAR(200)') as UpdateResultDescription
      FROM  MyTable
            outer apply MyTable.XML_Response.nodes('/IntegrationResults') AS IntegrationResults(n);
    

    【讨论】:

      【解决方案2】:

      谢谢大家,我找到了解决办法:

      .select(x => new
      {
         x.UserName,
         UpdateResult = x.MyTable.XML_Response.Element("UpdateResult").Value,
         UpdateResultDescription = x.MyTable.XML_Response.Element("UpdateResultDescription").Value,
      });
      

      【讨论】:

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