1

I've been crafting some generic, ORM-level utilities to make it easier for callers to do things in a consistent fashion with Entity Framework. The following is one of those methods:

        public static IQueryable<TEntity>
        QueryMany<TDbContext, TEntity, TOrder, TInclude>(TDbContext context, Expression<Func<TEntity, bool>> predicate,
            Expression<Func<TEntity, TOrder>> order, bool ascending, Expression<Func<TEntity, TInclude>> include, 
            int skipCount, int takeMax)
        where TEntity : class where TDbContext : DbContext
    {
        var query = context.Set<TEntity>().Where(predicate);

        if (include != null)
            query = query.Include(include);
        if (skipCount > 0)
            query = query.Skip(skipCount);
        if (takeMax > 0)
            query = query.Take(takeMax);
        if (order != null)
            query = ascending ? query.OrderBy(order) : query.OrderByDescending(order);

        return query;
    }

This makes it possible to query many items from any type of set in any context using any search predicate including any child property collection with skip and take functionality ordered ascending or descending by any given property. One may provide suitable "default" values for the parameters (e.g., null for the include and order, zeros for skip/take) to enable those bits of functionality selectively.

This works nicely until I want to include both children of the main TEntity type and children of the TInclude type. I'm well-accustomed to the usual, multi-level include syntax:

query.Include(parent => parent.Children.Select(child => child.Grandchildren)

But of course the template argument types in my generic method effectively pin it down to a single TEntity child property collection of a single type, TInclude.

My question is this: is there any way to provide more generalized include functionality in my generic method? It would be nice to feature arbitrary, multi-level include functionality, but so far I haven't found any approach that works.

UPDATE: I'm aware that one may also do includes with strings, but I'm not interested in that approach. I find it too hard to keep the types and strings synced up reliably as a code base grows and evolves. Please confine any answers strictly to LINQ statement/method syntax.

Phileosophos
  • 304
  • 1
  • 6
  • Generalizing the includes in the "string" way can be an alternative to you. Please refer [this](https://stackoverflow.com/questions/10822656/entity-framework-include-multiple-levels-of-properties/10823081#10823081) – Renato Lucas Chitolina Oct 10 '18 at 02:15
  • Sorry, I probably should have been more clear. I'll update the question to reflect that I explicitly do NOT want to use strings. It's just too bloody hard to keep them in sync with the types. – Phileosophos Oct 10 '18 at 19:09

0 Answers0