Reputation: 601
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;
Upvotes: 0
Views: 397
Reputation: 177163
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.
Upvotes: 1
Reputation: 3289
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.
Upvotes: 0