1

I'm migrating my code from EF6 to EF Core and in my generic repository I have the following method:

public virtual IQueryable<T> Get(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] include)
{
    try
    {
        if (include.Any())
        {
            var set = include.Aggregate<Expression<Func<T, object>>, IQueryable<T>>
                        (dbSet, (current, expression) => current.Include(expression));

            return set.Where(predicate).AsNoTracking<T>();
        }

        return dbSet.Where(predicate).AsNoTracking<T>();
    }
    catch (Exception ex)
    {
        throw new DatabaseException(ex);
    }
}

And in the concrete repositories:

public override User Get(Expression<Func<User, bool>> predicate)
{
    return base.Get(predicate,
        x => x.Rights.Select(g => g.Right);
}

In EF6 this was working perfectly. But now in EF Core I'm getting the following error:

EF Core error

How can I get this method to work again?

Ivan-Mark Debono
  • 15,500
  • 29
  • 132
  • 263
  • A DbSet already is a single-entity repository. A DbContext already is a multi-entity repository and Unit-of-Work. As for the error, EF Core isn't EF 6.The syntax `x.Rights.Select(g => g.Right)` was an EF6 quirk used to eagerly load 2nd-degree relations. That was unfortunate because there's no projection involved. There are SO questions asking why `.Include(x=>x.Select(g=>new {g......}` doesn't work. This was replaced by `ThenInclude` that specifies which nested relation to eagerly load – Panagiotis Kanavos Nov 23 '22 at 16:04
  • `ThenInclude` is explained in the [Eager Loading](https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager#including-multiple-levels) page, in the `Including Multiple Levels` section. Since EF Core 5 it's also possible to use [Filtered Includes](https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager#filtered-include) – Panagiotis Kanavos Nov 23 '22 at 16:08
  • @PanagiotisKanavos Is it possible to have the method above for EF Core and using `Include` and `ThenInclude`? – Ivan-Mark Debono Nov 23 '22 at 17:48
  • Maybe but that won't save you any code. You're already writing as much code as you'd write with `Include`. Perhaps a better option is to [auto-include navigations through model configuration](https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager#model-configuration-for-auto-including-navigations). You can configure your DbContext model so that specific relations are automatically loaded eagerly. This way, when you load a `User` you'll always get `Right` instances as well – Panagiotis Kanavos Nov 23 '22 at 17:58

0 Answers0