[英]How to query SQL Server table with XML column (as string) using Linq to SQL?
How can I use LINQ to SQL to query a table with an XML datatype column as an IQueryable? 如何使用LINQ to SQL查询具有XML数据类型列的表作为IQueryable?
SQL Server table: SQL Server表:
Id [int]
SomeData [xml]
An example of SomeData could be: SomeData的一个例子可能是:
<container><Person>Joe Smith</person></container>
In T-SQL, I can query the table like this to find employees with a specific nam,e : 在T-SQL中,我可以查询这样的表来查找具有特定nam的员工,e:
SELECT
*
FROM
[MyTable]
WHERE
SomeData.value('(//*[local-name()="Person"])[1]', 'varchar(max)') = 'Joe Smith'
Or to treat the xml as a string, to search for a string regardless of xml schema: 或者将xml视为字符串,以搜索不管xml架构的字符串:
SELECT
*
FROM
[MyTable]
WHERE
CONVERT(varchar(max), SomeData) like '%Joe Smith%'
Now I turn to LINQ to SQL, and want to perform the second query: 现在我转向LINQ to SQL,并希望执行第二个查询:
var myTable = db.MyTable.Where(x => x.SomeData.Value.Contains("Joe Smith"));
I get the error: 我收到错误:
"The member 'System.Xml.Linq.XElement.Value' has no supported translation to SQL.
I understand why I get the error, but is there a way to work around it? 我理解为什么我会收到错误,但是有办法解决它吗?
Being able to query the column as a string (with no concept of xml-structure) is completely fine in this case. 在这种情况下,能够以字符串形式查询列(没有xml结构的概念)是完全正常的。
创建一个将Xml列公开为varchar(...)并查询它的视图。
您可以使用System.Data.Linq.SqlClient.SqlMethods.Like()代替Contains。
var myTable = db.MyTable.Where(x => SqlMethods.Like(x.SomeData, "%Joe Smith%"));
将xml文件导入带有xml列的临时表,然后尝试解析该文件并将其放入关系表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.