15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

976 ❘ ChaPTer 34 .net prOGrAmminG with sQl server<br />

}<br />

class Program<br />

{<br />

static void Main()<br />

{<br />

using (ExamsEntities data = new ExamsEntities())<br />

{<br />

foreach (Exam item in db.Exams)<br />

{<br />

XElement exam = XElement.Parse(item.Info);<br />

Console.WriteLine("Exam: {0}", exam.Attribute("Number").Value);<br />

Console.WriteLine("Title: {0}", exam.Element("Title").Value);<br />

Console.Write("Course(s): ");<br />

foreach (var course in exam.Elements("Course"))<br />

{<br />

Console.Write("{0} ", course.Value);<br />

}<br />

Console.WriteLine();<br />

}<br />

}<br />

}<br />

}<br />

The ADO.<strong>NET</strong> Entity Framework <strong>and</strong> LINQ to XML are explained in Chapter 31, “ADO.<strong>NET</strong> Entity<br />

Framework,” <strong>and</strong> Chapter 33, “Manipulating XML,” respectively.<br />

querying the data<br />

Up until now, you haven’t seen the really great features of the XML data type. SQL SELECT statements can<br />

be combined with XML XQuery.<br />

A SELECT statement combined with an XQuery expression to read into the XML value is shown here:<br />

SELECT [Id], [Number], [Info].query('/Exam/Course') AS Course FROM [Exams]<br />

The XQuery expression /Exam/Course accesses the Course elements that are children of the Exam<br />

element. The result of this query returns the IDs, exam numbers, <strong>and</strong> courses:<br />

1 70-502 6460<br />

2 70-562 23106463<br />

3 70-561 23106464<br />

With an XQuery expression, you can create more complex statements to query data within the XML<br />

content of a cell. The next example converts the XML from the exam information to XML that lists<br />

information about courses:<br />

SELECT [Info].query('<br />

for $course in /Exam/Course<br />

return<br />

<br />

{ data(/Exam[1]/@Number) }<br />

{ data($course) }<br />

')<br />

AS Course<br />

FROM [Exams]<br />

WHERE Id=2<br />

Here, just a single row is selected with SELECT [Info]. FROM Exams WHERE Id = 2. With the result<br />

of this SQL query, the for <strong>and</strong> return statements of an XQuery expression are used. for $course<br />

in /Exam/Course iterates through all Course elements. $course declares a variable that is set with every<br />

iteration (similar to a <strong>C#</strong> foreach statement). Following the return statement, the result of the query for<br />

every row is defined. The result for every course element is surrounded by the element. Embedded<br />

inside the element are <strong>and</strong> . The text within the element is defined with<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!