I am using Entity Framework 4.1 Code First and am also using the PredicateBuilder so that I can build predicate expressions across multiple Specification classes (using the Specification pattern). I am able to properly build a predicate and apply it to a DbSet, and the data I get is what I expect. However, no matter what I try, it's always lazy loading. This is a simple example of how I'm building the predicate and applying 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();
Like I said above, I'm getting the data back that I want, but it ignores the Include.
Does anyone have any ideas?
Hi jumping in late on this, but had the same issue with using an extension Include method when using LinqKits predicate builder. The problem as referred to in the previous answer is that casting LinqKits ExpandableQuery to ObjectQuery (as required by the Include extension) results in null.
However found this link http://petemontgomery.wordpress.com/2011/02/10/a-universal-predicatebuilder/ which is a Predicate builder which doesn't use AsExpandable to perform the search and hence the Include method can be used on it. Although the solution above also worked for me this different predicate builder allowed me to keep my code cleaner/more consistent
It's probably changing the query shape. Try this workaround
HairColor[] hairColors = hairColorQuery.Where(hairColorPredicate)
.Select(hc => new
{
HairColor = hc,
Parents = hc.Parents // eager load
})
.AsEnumerable()
.Select(hc => hc.HairColor);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With