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.

object Query ❘ 877<br />

The following sections of this book make use of a Formula1 database where you can see the entities created<br />

from the designer in Figure 31-7.<br />

figure 31-7<br />

Queries can be defined with the ObjectQuery class, or the class that derives from it: ObjectSet.<br />

Let’s start with a simple query to access all Racer entities. The Racers property of the generated<br />

Formula1Entities class returns a ObjectSet:<br />

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

{<br />

ObjectSet racers = data.Racers;<br />

Console.WriteLine(racers.Comm<strong>and</strong>Text);<br />

Console.WriteLine(racers.ToTraceString());<br />

}<br />

The Entity SQL statement that is returned from the Comm<strong>and</strong>Text property is shown here:<br />

[Formula1Entities].[Racers]<br />

code snippet Formula1Demo/Program.cs<br />

And this is the generated SELECT statement to retrieve the records from the database that is shown by the<br />

ToTraceString() method:<br />

SELECT<br />

[Extent1].[Id] AS [Id],<br />

[Extent1].[Firstname] AS [Firstname],<br />

[Extent1].[Lastname] AS [Lastname],<br />

[Extent1].[Country] AS [Country],<br />

[Extent1].[Starts] AS [Starts],<br />

[Extent1].[Wins] AS [Wins]<br />

FROM [dbo].[Racers] AS [Extent1]<br />

Instead of accessing the Racers property from the object context, you can also create a query with the<br />

CreateQuery() method:<br />

ObjectQuery racers = data.CreateQuery("[Formula1Entities].[Racers]");<br />

This is similar to using the Racers property.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!