Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 429
Dylan Vester Avatar asked Dec 13 '22 12:12

Dylan Vester


2 Answers

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

like image 125
clarkio Avatar answered Apr 06 '23 01:04

clarkio


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);
like image 45
Craig Stuntz Avatar answered Apr 05 '23 23:04

Craig Stuntz