Usage of EntityFrameworkQueryableExtensions.ThenInclude in EF Core

c# entity-framework entity-framework-core

Question

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?

1
0
6/7/2017 8:02:46 PM

Popular Answer

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

0
8/16/2017 1:03:11 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow