Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework references not loading automatically

In the ADO.Net Entity Framework, I have an object which has 4 references to other objects. For some reason, when I query those references, two of them load automatically (as expected), and two of them always return null.

Bizarrely enough, when I manually ask the references to load, they load just dandy.

As an example:

if (account.HoldingEntity == null && 
    account.HoldingEntityReference.EntityKey != null) {

    account.HoldingEntityReference.Load();
    account.HoldingEntity = account.HoldingEntityReference.Value;
}

When I first check the HoldingEntity it is always null, however the Load will return the HoldingEntity without problem.

Any clues?

Thanks!

like image 763
gerrod Avatar asked Jun 23 '09 11:06

gerrod


2 Answers

Using ADO.NET Entities, you need to specify what entities you want to load automatically with Include, as in

Dim entity = (From e in db.Entities.Include("SubEntity"))
like image 153
Paulo Santos Avatar answered Oct 17 '22 15:10

Paulo Santos


As others have said you need to .Include() in v1 to avoid needing to call .Load()

In 4.0 you will be able to set DeferredLoadingEnabled on your ObjectContext (I think we are changing this name to the more appropriate LazyLoadingEnabled in time for Beta2).

As for why you get 2 relationships already loaded anyway. That is probably a side-effect of something called Relationship Fix-up.

When two related entities are in the same Context, they automatically get their relationship's fixed to point to each other. So if (as I suspect) 2 of the 4 entities are already in your context, when you do the query, you will end up in a situation where 2 of your relationships are loaded, even though you didn't call .Include() or .Load().

Hope this helps

Cheers Alex

like image 23
Alex James Avatar answered Oct 17 '22 15:10

Alex James