Ef core include for many-to-many in the generic repository

Viewed 282

I have many-to-many relationship in the DB. Typical realization with the eager loading in EF Core of GetAll method is:

    dbContext
    .DbSet<Book>
    .Include(e => e.BooksAuthors)
    .ThenInclude(ba => ba.Author)

But in case of generic repository I pass params Expression<Func<T, object>>[] includes as a parametr to the GetAll.

But the problem is, that with the help of

public static IQueryable<T> IncludeMultiple<T>(
   this IQueryable<T> query,
   params Expression<Func<T, object>>[] includes)
            where T : class
        {
            if (includes != null)
            {
                query = includes.Aggregate(query,
                    (current, include) => current.Include(include));
            }

            return query;
        }

I can load only BooksAuthors, not the next level of nesting. How to pass ThenInclude as a parametr?

1 Answers

You can use the string version of include

public static IQueryable<T> IncludeMultiple<T>(
   this IQueryable<T> query,
   params string[] includes)
            where T : class
        {
            if (includes != null)
            {
                query = includes.Aggregate(query,
                    (current, include) => current.Include(include));
            }

            return query;
        }

and your include would be

dbContext.DbSet<Book>.IncludeMultiple("BooksAuthors.Author")
Related