0

I have the following scenario (combined in one line)

var User = db.Entry(obj).Collection(collection).Query().Where(/*some condition*/).FirstOrDefault(/*some condition*/);

lets assume that User Object has Posts as a virtual attribute (to eagerly load them) the result of the previous line loads only ONE post for that user while if i did one of the following :

var Users = db.Entry(obj).Collection(collection).Query().ToList().Where(/*some condition*/).FirstOrDefault(/*some condition*/);
//added ToList() after the Query method
//OR
db.Users.Where(/*full condition*/).FirstOrDefault()
//OR
db.Users.FirstOrDefault(/*full condition*/)

all of these loads all the posts for the user, what i'm missing in the first query, and how can i eagerly load all the posts through it?

Hilmi
  • 3,411
  • 6
  • 27
  • 55

1 Answers1

3

Try adding .Include(VirtualPropertyToEagerLoad) after the .Where in your first query.

See this MSDN post on using eager loading.

ElliotSchmelliot
  • 7,322
  • 4
  • 41
  • 64
  • 4
    Using `.Include()` I highly recommend to use Lambda expressions instead of magic strings. You have to use the namespace `System.Data.Entity` for lambda expressions for the method include [LINK](http://romiller.com/2010/07/14/ef-ctp4-tips-tricks-include-with-lambda/) – boindiil Aug 10 '13 at 09:40
  • but do you know why it loaded one one entry? – Hilmi Aug 10 '13 at 10:32
  • Im not positive but my guess is that your first query doesn't hit all of the items in the collection (and thus doesn't load their nav properties). Whereas your 1st working query hits the entire collection through ToList, and your 2nd and 3rd working queries both access db.Users, which is the entirety of the object collection. – ElliotSchmelliot Aug 10 '13 at 18:15