I’ve an Asp.net MVC website, in which I’m using entity framework in my data store to access the database(with POCO entities).
I don’t why but sometimes, it’s looks like the lazy loading is just not done:
example of code not working:
using(BusinessEntities context = new BusinessEntities()){
User user = context.Users.First(u=>u.Id == parameterId);
foreach(Post post in user.Posts){//user.Posts is null here and thrown an exception
//.. doing some things
}
}
But if I do this, it perfeclty works
using(BusinessEntities context = new BusinessEntities()){
User user = context.Users.Include("Posts").First(u=>u.Id == parameterId);
foreach(Post post in user.Posts){//user.Posts is null here and thrown an exception
//.. doing some things
}
}
But I don’t understand why the lazy loading doesn’t work:
- Context isn’t disposed
- It’s not a project anonym object or something like that
- I know there is a lot of places in my code where I didn’t have to indicate this .Include and doing relative works
- I’ve the Lazy Loading Enabled set to True on my edmx model
What could leads to this behavior?
Declare
Postsproperty asvirtualso that proxy entity created by EF can lazy load the propety.