3

I am trying to learn LINQ for a project. But I am a little confused by the Include method. What is it used for? What is the difference between the following two initializations of the album variable?

var album = storeDB.Albums.Include("Artist").ToList();
var album = storeDB.Albums.ToList();
Jan
  • 15,802
  • 5
  • 35
  • 59
ankit0311
  • 735
  • 3
  • 10
  • 20

2 Answers2

7

Include is an extension method which is used by EF to enable Eager Loading of your Entities.

In the first case, by specifying Include("Artist"), when you retrieve Album entities from your Albums set, you are instructing LINQ to also retrieve the associated Artist entity (usually associations are through foreign keys in the database, although you can associate in your model as well).

In the second case, you aren't pulling through any related entities when Albums are fetched.

Note that as of Entity Framework 4.1 and onwards, there is a preferred mechanism for using Include which takes a lambda, so the string associations become strongly typed, i.e.:

var album = storeDB.Albums.Include(alb => alb.Artist).ToList();

Just remember to import System.Data.Entity when using the lambda extension.

Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285
  • So in the second case, if I try to access the Artist information, there will be another DB lookup, while there will be no DB lookup in the first case? – ankit0311 Nov 23 '12 at 09:20
  • @ankit0311 IFF you have enabled lazy loading, then yes, a second call will be made to fetch Artist information on a 'just in time' basis (and if you haven't, `Album.Artist` will be null). – StuartLC Nov 23 '12 at 09:32
0

The two statements are used for different purposes, the first one is to use Eager loading, that is, loading all the objects belonging to your entity at once (instead of making another query later),

the second one gives you the result so you can hold it in a ienumerable iterator instead of IQueryable object which is more common type for Linq

Jorge Alvarado
  • 2,664
  • 22
  • 33