I’m using Entity Framework 4.1, and I’m trying to select an entity while also including one of its related collections of entities. This is the standard way of doing this with LINQ. (MacAddressPool is one-to-many with AllowedPartNumbers.)
var query =
from p in MacAddressPools.Include( "AllowedPartNumbers" )
where p.MacAddressPoolID == 2
select p;
var pool = query.FirstOrDefault();
Console.WriteLine( pool.AllowedPartNumbers.IsLoaded );
"True"
Instead, I might want to do this to get other data at the same time:
var query =
from p in MacAddressPools.Include( "AllowedPartNumbers" )
where p.MacAddressPoolID == 2
select new
{
Pool = p,
AssignedMacAddressCount = pool.MacAddressAssignments.Count( a => a.AssignedDate != null )
};
var pool = query.FirstOrDefault().Pool;
Console.WriteLine( pool.AllowedPartNumbers.IsLoaded );
"False"
Why is the related entity collection not loaded this time? It doesn’t matter if I use an anonymous type or some class. It won’t load the AllowedPartNumbers. The SQL command that is used doesn’t even join the AllowedPartNumbers table.
I discovered that I can do this:
var query =
from p in MacAddressPools
where p.MacAddressPoolID == 2
select new
{
Pool = p,
AllowedPartNumbers = p.AllowedPartNumbers,
AssignedMacAddressCount = pool.MacAddressAssignments.Count( a => a.AssignedDate != null )
};
var pool = query.FirstOrDefault().Pool;
Console.WriteLine( pool.AllowedPartNumbers.IsLoaded );
"True"
Even though I’m just going to ignore that AllowedPartNumbers property on my anonymous type, having it there makes LINQ to Entities populate the AllowedPartNumbers property on the pool itself. I don’t even need the .Include().
Is there any reason for this strange behavior?
Include()is not guaranteed to work in subqueries and projections. You can find a detailed description of this issue at the MSDN forum and a related post by Shawn Wildermuth: Caution when Eager Loading in the Entity Framework.