Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 24. Applying LINQ > GENERATING XML FROM DATABASES

24.10. GENERATING XML FROM DATABASES

XML is often used to communicate data between client and server machines or between "tiers" in a multitier application. It is quite common to query for some data in a database, and then produce an XML document or fragment from that data to pass to another tier. In the following Try It Out, you create a query to find some data in the Northwind sample database, use LINQ to SQL to query the data, and then use LINQ to XML classes to convert the data to XML.

TRY IT OUT: Generating XML from Databases

Follow these steps to create the example in Visual Studio 2010:

  1. Create a new console application called BegVCSharp_24_6_XMLfromDatabase in the directory C:\BegVCSharp\Chapter24.

  2. As described in the "First LINQ to Data Query" example at the start of this chapter, add a new data source named Model1.edmx to the project, and then add a connection to the Northwind sample database.

  3. Compile your program so that the classes and properties defined in Model1.edmx will be available via IntelliSense when editing the code in the next steps.

  4. Open the main source file Program.cs.

  5. Add a reference to the System.Xml.Linq namespace to the beginning of Program.cs as shown:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml.Linq;
    using System.Text;

  6. Add the following code to the Main() method in Program.cs:



    static void Main(string[] args)
    {
    
                NORTHWNDEntities northWindEntities = new NORTHWNDEntities();
    
                XElement northwindCustomerOrders =
                   new XElement("customers",
                     from c in northWindEntities.Customers.AsEnumerable()
                     select new XElement("customer",
                        new XAttribute("ID", c.CustomerID),
                        new XAttribute("City", c.City),
                        new XAttribute("Company", c.CompanyName),
                            from o in c.Orders
                            select new XElement("order",
                                new XAttribute("orderID", o.OrderID),
                                new XAttribute("orderDay",
                                                    o.OrderDate.Value.Day),
                                new XAttribute("orderMonth",
                                                    o.OrderDate.Value.Month),
                                new XAttribute("orderYear",
                                                    o.OrderDate.Value.Year),
                                new XAttribute("orderTotal",
                                    o.Order_Details.Sum(od => od.Quantity * od.UnitPrice))
                              ) //end order
                            ) // end customer
                ); // end customers
    
                string xmlFileName =
                @"C:\BegVCSharp\Chapter24\Xml\NorthwindCustomerOrders.xml";
                northwindCustomerOrders.Save(xmlFileName);
    
                Console.WriteLine("Successfully saved Northwind customer orders to:");
                Console.WriteLine(xmlFileName);
                Console.Write("Program finished, press Enter/Return to continue:");
                Console.ReadLine();}
    
    					  

    Code snippet BegVCSharp\Chapter24\BegVCSharp246 XMLfromDatabase\Program.cs

  7. Compile and execute the program (you can just press F5 for Start Debugging). You will see the following output:

    Successfully saved Northwind customer orders to:
    C:\BegVCSharp\Chapter24\Xml\NorthwindCustomerOrders.xml
    Program finished, press Enter/Return to continue:

    Simply press Enter/Return to exit the program and make the console screen disappear. If you used Ctrl+F5 (Start Without Debugging), you may need to press Enter/Return twice.

How It Works

In Program.cs you added the reference to the System.Xml.Linq namespace in order to call the LINQ to XML constructor classes.

As described in the first part of the chapter, you created a data source for the Northwind sample database and then used Visual Studio 2010 to create a LINQ to Entities object model for the Northwind data. In the main program, you created an instance of the Northwind data context class to use the following mapping:

NORTHWNDEntities northWindEntities = new NORTHWNDEntities();

Your LINQ to Entities query uses the Northwind data context Customers member as a data source and drills down through the Customers, Orders, and Order Details tables to produce a list of all customer orders. However, because of deferred execution for LINQ to Entities, you convert the intermediate result to an in-memory LINQ to Objects enumerable type with the AsEnumerable() method on the Customer object. Finally, the query results are projected in the select clause of the query into a nested set of LINQ to XML elements and attributes:

XElement northwindCustomerOrders =
               new XElement("customers",
                from c in northWindDataContext.Customers.AsEnumerable()
                select new XElement("customer",
                   new XAttribute("ID", c.CustomerID),
                   new XAttribute("City", c.City),
                   new XAttribute("Company", c.CompanyName),
                   from o in c.Orders
                     select new XElement("order",
                        new XAttribute("orderID", o.OrderID),
                        new XAttribute("orderDay",
                                o.OrderDate.Value.Day),
                        new XAttribute("orderMonth",
                                o.OrderDate.Value.Month),
                        new XAttribute("orderYear",
                                o.OrderDate.Value.Year),
                        new XAttribute("orderTotal",
                            o.Order_Details.Sum(od => od.Quantity * od.UnitPrice))
                      ) //end order
                 ) // end customer
            ); // end customers

					  

To grab all the orders for a customer, you use a second LINQ query (from o in c.Orders. . .) nested inside the first one (from c in northWindDataContext.Customers. . .).

You divide the OrderDate field into its month, date, and year components to make the XML easier to query; you will see how this is used in the next example.

Finally, you save the generated XML to file as in the previous example:

string xmlFileName =
                  @"C:\BegVCSharp\Chapter24\Xml\NorthwindCustomerOrders.xml";
       northwindCustomerOrders.Save(xmlFileName);

       Console.WriteLine("Successfully saved Northwind customer orders to:");
       Console.WriteLine(xmlFileName);

					  

Now you will write a query against the XML file you just wrote to disk.



  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial