O'Reilly logo

Programming C# 4.0 by Jesse Liberty, Matthew Adams, Ian Griffiths

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

Queries

We’ve seen some simple LINQ-based examples for retrieving data from the database with the Entity Framework. Under the covers, the EF turns a LINQ query into a SQL query that the database understands. In fact, there are two ways of getting the EF to query the database for data: LINQ and something called Entity SQL. We’ve seen some simple LINQ to Entities examples already, but we’ll now look at it in more detail.

LINQ to Entities

The LINQ provider for the Entity Framework, LINQ to Entities, supports all of the standard LINQ operators we saw in Chapter 8, but it works a little differently. The idea of deferred execution is still present, and it’s even more important. The point at which you cause the LINQ query to execute—the instant at which your code first starts trying to use the results—is the point at which the EF will need to send a request to the database. So looking at the code from Example 14-3, the statement shown in Example 14-9 does not get anything from the database.

Example 14-9. Simple LINQ to Entities query expression

var orders = from order in dbContext.SalesOrderHeaders
             where order.OrderDate == orderDate
             select order;

As always with LINQ, a query expression only defines a query—orders is an object that knows what it’s supposed to return if anything happens to enumerate it. So it’s the foreach loop in Example 14-3 that kicks off the actual request.

The way the EF processes the request is different from how LINQ to Objects works. LINQ to Objects works by forming a ...

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