0

This is my POCO entities scenario:

Manufacturer (1) has Cars (*)

One Car entity has a navigation property to a Manufacturer entity.

One Manufacturer entity has a navigation property to a Cars collection

I need to query all Cars of a specified color, with their respective Manufacturer, so my EF query would be:

Context.Cars.Where(i=>i.Color=='White').Include("Manufacturer").ToList();

This is what I get: A list of Cars, with the Manufacturer correctly populated

The problem is that the Manufacturer entity brings it navigation property Cars populated as well:

Cars.FirstOrDefault().Manutefacturer.Cars is full of cars....

How can I get rid of this undesirable behavior?

Thanks a lot.

UPDATE #1: I do have the following properties set:

this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
hamiltonjose
  • 461
  • 5
  • 14

2 Answers2

1

The problem is that the Manufacturer entity brings it navigation property Cars populated as well: Cars.FirstOrDefault().Manufacturer.Cars is full of cars....

Yes, but only of white cars...

It's not an additional join in the database query that asks for the Cars collection of each loaded manufacturer. But just the cars that you loaded in your query - the white cars - are added to the collections of their respective manufacturer. The Entity Framework context does this when the loaded data get materialized to entities. It's called relationship fixup and you can't disable it. Here was a similar question and answer recently.

Community
  • 1
  • 1
Slauma
  • 175,098
  • 59
  • 401
  • 420
  • Thanks for pointing that this behavior is expected, yet I am not convinced that we have to live with this. Thanks anyway. – hamiltonjose May 23 '13 at 21:30
0

It sounds like you might have lazy loading enabled, which will automatically load navigation properties from the database the first time they're accessed.

You can disable it for your entire DbSet in the constructor:

public MyContext() : base()
{
  this.Configuration.LazyLoadingEnabled = false;
}

Then only the navigation properties you load manually with Include() will be present.

That said, if you're accessing the Cars property, you want it populated, don't you? And if you're not accessing it, then the lazy loading won't happen in the first place.

Jeremy Todd
  • 3,261
  • 1
  • 18
  • 17
  • Nice try, but I do have the property LazyLoadingEnabled = false.... And no, I just accessed the Cars property to check if it was being populated... I dont want this behavior... but thanks. – hamiltonjose May 23 '13 at 14:43