03.11.2016 Views

Beginning ASP.NET 4.5 in CSharp and VB Opsylum

Create successful ePaper yourself

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

Introduc<strong>in</strong>g Query Syntax x 515<br />

Order By genre.Name<br />

Select New With {genre.Name, genre.Reviews}<br />

Repeater1.DataSource = allGenres<br />

Repeater1.DataB<strong>in</strong>d()<br />

End Us<strong>in</strong>g<br />

End Sub<br />

C#<br />

us<strong>in</strong>g PlanetWroxModel;<br />

... // Class def<strong>in</strong>ition goes here<br />

protected void Page_Load(object sender, EventArgs e)<br />

{<br />

us<strong>in</strong>g (PlanetWroxEntities myEntities = new PlanetWroxEntities())<br />

{<br />

var allGenres = from genre <strong>in</strong> myEntities.Genres.Include("Reviews")<br />

orderby genre.Name<br />

select new { genre.Name, genre.Reviews };<br />

Repeater1.DataSource = allGenres;<br />

Repeater1.DataB<strong>in</strong>d();<br />

}<br />

}<br />

6. Save the changes to your page <strong>and</strong> then request it <strong>in</strong> the browser. You should see a result similar to<br />

that shown <strong>in</strong> Figure 14-6, where each genre appears as a group header above the lists with reviews.<br />

FIGURE 14-6<br />

How It Works<br />

You have two important th<strong>in</strong>gs to look at <strong>in</strong> this exercise. First of all,<br />

there’s the LINQ query that is used to get the genres <strong>and</strong> reviews from<br />

the database. This query (that uses Include("Reviews") to prevent<br />

lazy load<strong>in</strong>g as you saw earlier) creates a new anonymous type with two<br />

properties: the Name of the Genre as a Str<strong>in</strong>g <strong>and</strong> a collection of Review<br />

objects called Reviews. The class diagram for the new anonymous type<br />

could look like Figure 14-7.<br />

FIGURE 14-7

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

Saved successfully!

Ooh no, something went wrong!