tags:

views:

15

answers:

1

I am reading this asp.net article on building your first asp.net mvc 2 website and I came across a Linq query that uses the Include method in the query. I have used some linq, but I have never used the Include method and would like a better explanation. Does it translate to an join in linq? What is the benefit? Here is the query from the article:

var genreModel = storeDB.Genres
                        .Include("Albums")
                        .Single(g => g.Name == genre);

The article states that:

Entity Framework feature that allows us to specify other related entities we want loaded as well, called Query Result Shaping. We want to load the Albums for the matching Genre, so we'll query from Genres.Include("Albums") to indicate that we want related albums as well. This is more efficient, since it will retrieve both our Genre and Album data in a single database request.

I sort of understand what the author is saying above, but feel I would need a better example or explanation, especially since I have never used the Include method before.

+1  A: 

If you inspect the generated sql, you'll notice that the Albums table is joined in. It should look something like:

SELECT [t0].*, [t1].*
FROM Genres [t0]
LEFT JOIN Albums [t1] ON [t0].GenreId = [t1].GenreId
WHERE [t0].Name == @p0

When the results get back to the client side, the ObjectContext will turn the row-column shape into instances of Genres and Albums. These instances will be related hierarchically - the single Genre with all of its Albums.

Suppose this genre has 5 albums. The query will return 5 rows. The object context will create one instance of Genre (each of the 5 rows has the same Genre primary key value).

David B