Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / C# / April 2008

Tip: Looking for answers? Try searching our database.

LINQ to SQL as XML

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Marc S - 11 Apr 2008 19:41 GMT
I have a LINQ class that I can use to query data from my database. I
want to query the data directly into an XML string without defining
each field.

If I have a table Names like the following:

Table: Names
   Id int,
   LastName varchar(32),
   FirstName varchar(32)

Then I have a LINQ query that queries my DataContext:

var qry = from n in context.Names
 where n.Id == pId
 select n ;

I want to query the context as if to say
"select * from Names where Id = pId for XML AUTO"

If there a way to do that without manually creating an XElement?
Marc Gravell - 13 Apr 2008 00:41 GMT
LINQ is intended to be an object pipeline - as such, there is no
*immediate* way to do this - i.e. you can't impact the auto-generated
SQL to that extent short of writing your own impementation. You could
issue direct SQL, but that might defeat the purpose...

However! One option might be to feed the LINQ output into LINQ-to-SQL;
the SQL query won't have "FOR XML AUTO" in it, but the result should
be largely the same...

For example (and borrowing an idea [AsXAttributes*] slightly from Jon
Skeet's book [I'm sure he'll forgive me])...

*=the idea is Jon's, but no concrete implementation is offered in the
book (it may well be on the website - I didn't look); so any fault in
this alternative implementation is mine, not his - i.e. credit => Jon,
blame => me ;-p

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;
using ConsoleApplication13;

static class Program
{
   static void Main()
   {
       Application.EnableVisualStyles();
       using (NWindDataContext ctx = new NWindDataContext())
       {
           ctx.Log = Console.Out; // show SQL
           var suppliers = new XElement("suppliers",
               from supplier in ctx.Suppliers
               select new XElement(
                   "supplier",
                   supplier.AsXAttributes())
               );
           Console.WriteLine(suppliers);
       }
   }

   static IEnumerable<XAttribute>
       AsXAttributes(this object source)
   {
       if(source == null) throw new ArgumentNullException("source");
       foreach (PropertyDescriptor prop in
TypeDescriptor.GetProperties(source))
       {
           object value = prop.GetValue(source);
           if (value != null)
           {
               yield return new XAttribute(prop.Name, value);
           }
       }
   }
}
Marc Gravell - 13 Apr 2008 00:42 GMT
> LINQ output into LINQ-to-SQL
Should have read: LINQ-to-SQL output into LINQ-to-XML

Marc
Jon Skeet [C# MVP] - 13 Apr 2008 02:09 GMT
<snip>

> For example (and borrowing an idea [AsXAttributes*] slightly from Jon
> Skeet's book [I'm sure he'll forgive me])...
[quoted text clipped - 3 lines]
> this alternative implementation is mine, not his - i.e. credit => Jon,
> blame => me ;-p

Our code is almost identical - except I've just used PropertyInfo
instead of PropertyDescriptor. Oh, and I replace "_" with "-" in the
name, for the sake of some particular example I was interested in. I
also didn't bother with the null argument check - you're more
fastidious than I am, clearly :)

Here's the code (downloaded from http://csharpindepth.com/Downloads.aspx
as I don't have the original with me at the moment):

public static IEnumerable<XAttribute> AsXAttributes(this object data)
{
   foreach (PropertyInfo prop in data.GetType().GetProperties())
   {
       object value = prop.GetValue(data, null);
       if (value != null)
       {
           yield return new XAttribute
               (prop.Name.Replace("_", "-"), value);
       }
   }
}

Jon

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.