使用LINQ和XElement查询SQL表

问题描述 投票:1回答:2

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

MyTable(UserName varchar(50),XML_Response XML)

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

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

<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
2个回答
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);

1
投票

谢谢大家,我能够找到解决方案:

.select(x => new
{
   x.UserName,
   UpdateResult = x.MyTable.XML_Response.Element("UpdateResult").Value,
   UpdateResultDescription = x.MyTable.XML_Response.Element("UpdateResultDescription").Value,
});
© www.soinside.com 2019 - 2024. All rights reserved.