In EF, when you want to include a navigation property in the result of a query, you use Include(). Since some queries require calling this more than once, I tried to create a generic wrapper around this concept:
public IQueryable<T> FindAll<P>(params Expression<Func<T, P>>[] predicates) where P : class {
var entities = AllEntities();
foreach (var p in predicates) entities = entities.Include(p);
return entities;
}
And call it as such:
var customers = FindAll(q => q.Orders, q => q.Invoices, q => q.Contacts);
Questions:
- The function compiles, but when I call it: “The type arguments for method cannot be inferred from the usage. Try specifying the type arguments explicitly.” What am I doing wrong?
- If I get it to work, can I call
Include()the first time:var customers = FindAll(q => q.Orders, q => q.Invoices);and then again later in a separate step:customers = customers.Include(p => p.Invoices);or will that result in poor performance such that I should do the includes in one go?
EDIT:
JonSkeet’s answer is correct, of course, and yet there is this solution which seems to do what I want. Not sure why it works however. Is it because of the Aggregate() function?
Fundamentally, I think you’ve got a problem – assuming that
q.Orders,q.Invoicesandq.Contactsreturn different types, you can’t express what you want to happen. You probably want something like:… so you want a different value for
Pfor each predicate. But you’re calling a single method, providing a single type argument forP.It’s not clear that this is really giving you much benefit anyway… couldn’t you just write:
I’d say that’s clearer and it gets round the “multiple type parameters” problem.