J4N
J4N

Reputation: 20717

Entity framework: Any reason why my related entity isn't "lazy-loaded "?

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:

What could leads to this behavior?

Upvotes: 0

Views: 214

Answers (2)

Eranga
Eranga

Reputation: 32437

Declare Posts property as virtual so that proxy entity created by EF can lazy load the propety.

Upvotes: 1

Matija Grcic
Matija Grcic

Reputation: 13381

Please install EF 4.1 from http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=8363 to stop using magic strings inside Include. Add

using System.Data.Entity;

to your using statements.

Then write the following query:

using(BusinessEntities context = new BusinessEntities()){
   var user = context.Users.Include(p=>p.Posts).FirstOrDefault(u=>u.Id == parameterId);
   if(user != null)
   {
      foreach(Post post in user.Posts)
      {
         //.. do something
      }
   }
}

For more information refer to the following http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx

Upvotes: 0

Related Questions