Can LINQ to SQL query an XML field DB-serverside? Can LINQ to SQL query an XML field DB-serverside? xml xml

Can LINQ to SQL query an XML field DB-serverside?


Now that is an interesting question.

Right now, you cannot instruct SQL Server to perform XML functions directly from Linq. However, you can get Linq to use user defined functions...so, you could setup a udf to process the xml, get the right data, etc, and then use that in your Linq expresion. This will execute on the server and should do what you want. There's an important limitation, though: The XML path you're looking for (the first parameter to xmlColumn.value or similar) has to be built into the function because it has to be a string literal, it can't be built from an input parameter (for instance). So you can use UDFs for getting fields you know about when writing the UDF, but not as a general-purpose way to get data from XML columns.

Check out the Supporting User Defined Functions (UDFs) section of Scott Gutherie's excellent Blog series on Linq to SQL for more info on implementation.

Hope this helps.


To clarify Daniel's answer - you cannot use a function to do this unless the XPath part of the query is fixed. See my blog entry on this: http://conficient.wordpress.com/2008/08/11/linq-to-sql-faq-xml-columns-in-sql/

Basically you cannot query an xml column via LINQ to SQL. Although it returns an XElement type you cannot do any SQL translations when trying to filter on this column.

LINQ to SQL does support using UDFs - but SQL itself will not allow you to use a parameter string in a XML xpath query - it has to be a string literal. That means it can work if the XPath is fixed at design time, but not if you wanted to be able to pass a variable XPath statement.

This leads to only two other alternative ways of doing it: inline SQL statement (which negates the value of having LINQ) and writing a SQL Library function in .NET CLR to do this.


This is not the best, not for all queries, and not completely linq, but works and is fast :

an xml sql field accept the ".ToString", so you can do :

Dim txt as String = "<File>3</File>"Return (From P In DC.LPlanningRefs Where P.Details.ToString.Contains(txt) Select P).FirstOrDefault

I use it to limit lines returned, and then, I look for each returned lines