0

I tried to define a generic loading method. I call this generic loading method with an array of expressions like this:

var includes = new Expression<Func<CatalogItem, object>>[]
    {
        ci => ci.Catalog.Select(ci => ci.Supplier.Region),
        ci => ci.Test
    }

In the method I create an IQueryable:

IQueryable<TAggregateRoot> queryable = dbContext.Set<TAggregateRoot>();

Then for each Expression I want to load the respective data like this:

foreach (var include in includes)
    {
        queryable = queryable.Include(include);
    }

But this only works when the Expression is only one level. With multiple levels it throws an error.
Since there is no ThenInclude I have to use the EntityFrameworkQueryableExtensions. I tried it like this

queryable = EntityFrameworkQueryableExtensions.ThenInclude(queryable, include);

But this does not work either.

I cannot find any documentation to this problem. How do I solve this problem and how do I use EntityFrameworkQueryableExtensions.ThenInclude?

Palmi
  • 2,381
  • 5
  • 28
  • 65

1 Answers1

1

Instead of passing an expression to the Include() method, there are two overloads you can use that take strings.

The first takes either a single property or multi-level properties like so:

Include("property1")

OR

Include("property1.property2.property3")

The second takes advantage of the nameof() method like so:

Include(nameof(property1), nameof(property2), nameof(property3))

And if you have a generic loading method that takes an array of strings to iterate over and "Include" (in precisely the same fashion you are iterating over your array right now), then you can use the first overload (one string) and do something like this:

MyGenericRepo.MySetInclude(new string[] {$"{nameof(ParentEntity.ChildEntity)}.{nameof(ChildEntity.GrandchildEntity)}"});

So you are still only using the one Include() method without adding any additional logic to your repository, but you can now "include" as many levels as you wish.

To see the origins of these overloads, you can check it out here

andreisrob
  • 1,615
  • 15
  • 11