Search code examples
sqlsql-serverlinq-to-sqlxqueryexpression-trees

Combine SQL with XQuery and Linq To SQL


How to efficiently combine a direct SQL query and Linq To SQL query? Linq To SQL doesn't support XQuery. So I have to combine the results of a SQL with XQuery and column based Linq To SQL?

Any pointers is appreciated. Thanks!


Solution

  • Chris Cavanagh has a couple blog posts that provide options for leveraging XQuery in conjunction with LINQ to SQL.

    1. SQL Server XQuery with LINQ to SQL provides the framework for a solution that would involve embedding the XQuery into user-defined functions, which can be accessed from LINQ to SQL

    2. Modifying LINQ to SQL command text and Modifying LINQ to SQL command text again provide a way to extend LINQ to SQL's query execution, by manipulating the generated command text to support XQuery constructs.

    The end result is you can actually use XQuery directly from your DataContext, by writing code that looks like:

    var results = from r in MyXmlFieldTable
       let date = context.XQueryDateTime( r.XmlValues, "MyContainer/MyDateTime" )
       where date < DateTime.Now.AddDays( -5 )
       select new
       {
           Date = date,
           FirstName = context.XQueryString( r.XmlValues, "MyContainer/FirstName" ),
           LastName = context.XQueryString( r.XmlValues, "MyContainer/LastName" )
       };
    

    (However, if you find that you need to do this kind of thing a lot, there's a chance you will be better off with a document database like MongoDB or RavenDB, which are meant for working with hierarchical/post-relational models)

    As a side note about XQuery and SQL in general, you will get varying degrees of support in different versions. Specifically, the XQuery support in SQL 2005 is a limited subset of the support in later versions.