Question

I'm using Entity Framework 4 in Visual Studio 2010, with C#.

I have a method used in a repository that returns a object set with various navigation properties included. Up until recently, this method looked like this...

private IEnumerable<VRTSystem> GetSystems() {
  return ctx
    .Include(s => s.Customer.CustomerType)
    .Include(s => s.VRTSystemProductConfigurations);
}

...where ctx is an ObjectSet of generic type VRTSystem. The full method had a lot more .Include()s than this, but this is enough to show the point.

This worked fine, however I needed to add some code to ensure that only VRTSystemProductConfigurations that had the Active flag set to true were returned. Following the advice commonly given for such situations, I changed the code to look like this...

private IEnumerable<VRTSystem> GetSystems() {
  return ctx
    .Include(s => s.Customer.CustomerType)
    .Include(s => s.VRTSystemProductConfigurations)
    .Select(s => new {
      System = s,
      VRTSystemProductConfigurations = s.VRTSystemProductConfigurations.Where(pc => pc.Active)
    })
    .Select(s => s.System);
}

However, this new version does not include any of the navigation properties, they are all null.

Anyone any idea why?

Was it helpful?

Solution

This is because Entity Framework is not entirely stupid. It sees that in the end only Systems are queried, so it cuts everything in between and returns Systems only. And part of the trick you're executing here is to disable lazy loading, so the navigation properties are null and will remain null.

You have to remove the last Select out of the scope of the EF query provider by adding an AsEnumerable:

return ctx
.Include(s => s.Customer.CustomerType)
.Select(s => new {
  System = s,
  VRTSystemProductConfigurations = s.VRTSystemProductConfigurations.Where(pc => pc.Active)
})
.AsEnumerable() 
.Select(s => s.System);

And you don't want to include VRTSystemProductConfigurations, because that's the collection you want to load partly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top