15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

884 ❘ ChaPTer 31 AdO.net entity frAmewOrk<br />

}<br />

foreach (Racer r in racers)<br />

{<br />

Console.WriteLine("{0} {1}", r.Firstname, r.Lastname);<br />

}<br />

code snippet Formula1Demo/Program.cs<br />

This is the result of accessing the Formula1 database:<br />

Michael Schumacher<br />

Alain Prost<br />

Ayrton Senna<br />

You can also define a LINQ query to access relations as shown here. Variable r references racers, variable<br />

rr references all race results. The filter is defined with the where clause to retrieve only racers from<br />

Switzerl<strong>and</strong> who had a race position on the podium. To get the podium finishes, the result is grouped, <strong>and</strong><br />

the podium count calculated. Sorting is done based on the podium finishes:<br />

using (var data = new Formula1Entities())<br />

{<br />

var query = from r in data.Racers<br />

from rr in r.RaceResults<br />

where rr.Position = 1 &&<br />

r.Country == "Switzerl<strong>and</strong>"<br />

group r by r.Id into g<br />

let podium = g.Count()<br />

orderby podium descending<br />

select new<br />

{<br />

Racer = g.FirstOrDefault(),<br />

Podiums = podium<br />

};<br />

foreach (var r in query)<br />

{<br />

Console.WriteLine("{0} {1} {2}", r.Racer.Firstname, r.Racer.Lastname,<br />

r.Podiums);<br />

}<br />

}<br />

The names of three racers from Switzerl<strong>and</strong> are returned when you run the application:<br />

Clay Regazzoni 28<br />

Jo Siffert 6<br />

Rudi Fischer 2<br />

summary<br />

In this chapter, you’ve seen the features of the ADO.<strong>NET</strong> Entity Framework. The ADO.<strong>NET</strong> Entity<br />

Framework is based on mapping that is defined by CSDL, MSL, <strong>and</strong> SSDL — XML information that<br />

describes the entities, the mapping, <strong>and</strong> the database schema. Using this mapping technique, you can create<br />

different relation types to map entity classes to database tables.<br />

You’ve seen how the object context keeps knowledge about entities retrieved <strong>and</strong> updated, <strong>and</strong> how the<br />

changes can be written to the store.<br />

LINQ to Entities is just a facet of the ADO.<strong>NET</strong> Entity Framework that allows you to use the new query<br />

syntax to access entities.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!