views:

158

answers:

1

Imagine this case:

var locations = from Locations in this.LocationDataContext.Locations
                                      .Include("ChildLocations")                      
                where
                     (Locations.LocationType.ID == 3) 
                select
                     Locations;

This query will load all locations with type == 3 and all the related child locations, ok. But what i'm trying to figure out is how to filter the child locations that are being loaded. What if location have 3milion child locations?

Maybe something like this? (doesnt work because ChildLocations is a set of entities)

var locations = from Locations in this.LocationDataContext.Locations
                                      .Include("ChildLocations")                      
                where
                     (Locations.LocationType.ID == 3) &&
                     (Locations.ChildLocations.LocationType.ID == 2)
                select
                     Locations;

Thank you.

A: 

The Entity Framework will never materialize a partially-complete instance. You cannot, in other words, materialize a Location with only some of its ChildLocations. This would be an "incomplete" object, and the Entity Framework does not allow this.

However, there are workarounds. If you only need the information from the ChildLocations and not from the Location itself, just select that:

from Locations in this.LocationDataContext.Locations
where Locations.LocationType.ID == 3
from ChildLocation in Locations 
where ChildLocation.LocationType.ID == 2
select ChildLocation;

In this case, since we are only selecting the ChildLocations, it is OK to only select a few of them, since they can be materialized completely. It is only when materializing the Location that we need all of the children.

Another workaround is to materialize partial Location information into an anonymous type. This allows you to get information about both the Location and some of the ChildLocations without violating the rule that instances can only be materialized in their complete form. Since you're not actually materializing a real Location, there is no requirement to materialize the entire thing:

from Locations in this.LocationDataContext.Locations
where Locations.LocationType.ID == 3
select new 
{
    ID = Locations.ID,
    LocationType= Locations.LocationType
    ChildLocations = from ChildLocation in Locations 
                     where ChildLocation.LocationType.ID == 2
                     select ChildLocation
}
Craig Stuntz