Entity Framework 4.1 Code First - Include is ignored when using LinqKit PredicateBuilder

I am using Entity Framework 4.1 Code First and also using PredicateBuilder so that I can create predicate expressions in several specification classes (using the specification template). I can build the predicate correctly and apply it to the DbSet, and the data that I get is what I expect. However, no matter what I try, it is always a lazy load. This is a simple example of how I construct a predicate and apply it.

IQueryable<HairColor> hairColorQuery = Context.Set<HairColor>().AsExpandable(); Expression<Func<Parent, bool>> parentPredicate = PredicateBuilder.And(PredicateBuilder.True<Parent>(), p => p.NameLast.StartsWith("V")).Expand(); Expression<Func<HairColor, bool>> hairColorPredicate = PredicateBuilder.And(PredicateBuilder.True<HairColor>(), h => h.Parents.AsQueryable().Any(parentPredicate)); HairColor[] hairColors = hairColorQuery.Where(hairColorPredicate).Include(h => h.Parents).ToArray(); 

As I said above, I get the data I want back, but it ignores Include.

Does anyone have any ideas?

+4
source share
2 answers

Hi, the latter recently, but had the same problem using the Include extension method when using the LinqKits predicate builder. The issue mentioned in the previous answer is that casting LinqKits ExpandableQuery to ObjectQuery (as required by the Include extension) results in null.

However, I found this link http://petemontgomery.wordpress.com/2011/02/10/a-universal-predicatebuilder/ , which is the creator of Predicate, which does not use AsExpandable to perform the search, and therefore the Include method can be used on it. Although the solution above also worked for me, this other predicate builder allowed me to keep my code cleaner / more consistent

+11
source

Probably a change in the request form . Try a workaround

 HairColor[] hairColors = hairColorQuery.Where(hairColorPredicate) .Select(hc => new { HairColor = hc, Parents = hc.Parents // eager load }) .AsEnumerable() .Select(hc => hc.HairColor); 
+2
source

All Articles