locked
EF & Lazy Loading RRS feed

  • Question

  •  

    Hi all.

     

    And another question. I've got 2 tables - Parts & Users. In Parts there is FK for UserId. In EF this FK was substituted by

    relation Parts.Users. The thing is if I call this:

     

    Entities en = new Entities();

    List<Parts> parts = en.Parts.ToList<Parts>();

     

    Parts p = parts.Find(part => part.PartId == 91058);

    Users user = p.Users;

     

    it will return null as user, but in this case:

     

    Entities en = new Entities();

    List<Parts> parts = en.Parts.ToList<Parts>();

     

    List<Users> users = en.Users.ToList<Users>();//!!!

     

    Parts p = parts.Find(part => part.PartId == 91058);

    Users user = p.Users;

     

    it will return a real instance of Users.

     

    I know something like this in LINQ2SQL when you should declare method DataContext.LoadXXX(YYY) if you want a relation loaded on demand. Is there anything like this in EF?

    Thursday, June 5, 2008 3:31 PM

Answers

  • You should be able to use p.UsersReference.Load() that you can call to bring related end into object context.

    To check whether the related end has been loaded, use p.UsersReference.IsLoaded.

     

    BTW. You may want to take a look at EFLazyLoading sample library which does transparent lazy loading for Entity Framework and eliminates the need to call Load()/IsLoaded in your application.

    Thursday, June 5, 2008 4:38 PM

All replies

  • You should be able to use p.UsersReference.Load() that you can call to bring related end into object context.

    To check whether the related end has been loaded, use p.UsersReference.IsLoaded.

     

    BTW. You may want to take a look at EFLazyLoading sample library which does transparent lazy loading for Entity Framework and eliminates the need to call Load()/IsLoaded in your application.

    Thursday, June 5, 2008 4:38 PM
  • Well, thanks for the link.

    However I'm trying now to use Perseus (EntityBag - http://code.msdn.microsoft.com/entitybag) - it gives the best fit for my needs.

    Friday, June 13, 2008 9:17 AM