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

Querying Contents of a Collection Navigation Property

So far you’ve looked at loading the entire contents of a collection navigation property so that you can work with the data in memory. If you wanted to filter the contents of a navigation property you could do this after you’d brought everything into memory, using LINQ to Objects. However, if you are only interested in a subset of the contents, it may make sense to just bring the bits you are interested in into memory. Or if you just want a count, or some other calculation, it may make sense just to calculate the result in the database and not bring any of the data into memory.

Once you’ve used Entry and Collection to drill into a collection navigation property, you can then use the Query method to get a LINQ query representing the contents of that property. Because it’s a LINQ query, you can then do further filtering, sorting, aggregation, and the like.

Assume you wanted to find all Lodgings at the Grand Canyon that are less than ten miles from the nearest airport. You could just use LINQ to query the contents of the Lodgings property of the Grand Canyon, something like Example 2-27.

Example 2-27. In-memory query of a navigation property

private static void QueryLodgingDistance()
{
  using (var context = new BreakAwayContext())
  {
    var canyonQuery = from d in context.Destinations
                      where d.Name == "Grand Canyon"
                      select d;

    var canyon = canyonQuery.Single();

    var distanceQuery = from l in canyon.Lodgings
                  where l.MilesFromNearestAirport <= ...

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