O'Reilly logo

Programming Entity Framework: DbContext by Rowan Miller, Julia Lerman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using LINQ for Sorting, Filtering, and More

While this chapter will not be an exhaustive list of everything you can do with LINQ and Entity Framework, let’s take a look at the patterns used to achieve some common query tasks. Let’s say you want to print out the names of Destinations again, but this time you want them ordered alphabetically by Name. Add a new PrintAllDestinationsSorted method that uses a LINQ query to perform this sort (Example 2-6).

Example 2-6. Query for destinations sorted by name

private static void PrintAllDestinationsSorted()
{
  using (var context = new BreakAwayContext())
  {
    var query = from d in context.Destinations
                orderby d.Name
                select d;

    foreach (var destination in query)
    {
      Console.WriteLine(destination.Name);
    }
  }
}

The above code uses LINQ to create a query and then iterates the results of the query and displays the name of each destination. The query is expressed using a syntax that looks a little bit like SQL. You start by telling it what you want to select from (in our case, the Destinations set on our context). You give the set a name so that you can refer to it throughout the rest of the query (in our case that name is d). Following this, you use operators such as orderby, groupby, and where to define the query. Finally you specify what you want returned using the select operator. In our case we want the actual Destination objects returned, so we specify the name that we gave the set in the first line.

Remember that Entity Framework won’t execute the query ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required