Entity Framework Core - Include Multiple Levels of a Property for a Collection

c# entity-framework-core

Question

I want to know how I can include multiple levels of a property for a collection in Entity Framework Core.

An example of my situation:

public class A
{
    public ICollection<B> listB ...
}

public class B
{
    public C c ...
}

The answers provided in Entity Framework - Include Multiple Levels of Properties for EF Core do not cover the case in which the nested properties are collections, when I try:

var wtv = Context.AItems.Include(a => a.listB).ThenInclude(b => b. )

I only have access to the properties of the ICollection itself (listB) and not the properties of the B objects contained in it, so that I could include the C object in it contained in it.

I managed to do this manually (being a lot more verbose than I would prefer), loading the B objects separately and including what I want in it, and only then add them to A's listB. However, In my real-life situation the properties I want to include in levels below are also for collections so this becomes less and less pratical. Is there a simpler and more elegant way of doing this?

1
1
10/26/2018 3:40:45 AM

Accepted Answer

There are two overloads of ThenInclude, one for the case the previous navigation property is a single entity, and another one for collections:

public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>([NotNullAttribute] this IIncludableQueryable<TEntity, TPreviousProperty> source, [NotNullAttribute] Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class;

public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>([NotNullAttribute] this IIncludableQueryable<TEntity, IEnumerable<TPreviousProperty>> source, [NotNullAttribute] Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class;

You should be able to just use it like this:

Context.AItems.Include(a => a.listB).ThenInclude(b => b.c)

From Microsoft Docs:

Current versions of Visual Studio offer incorrect code completion options and can cause correct expressions to be flagged with syntax errors when using the ThenInclude method after a collection navigation property. This is a symptom of an IntelliSense bug tracked at https://github.com/dotnet/roslyn/issues/8237. It is safe to ignore these spurious syntax errors as long as the code is correct and can be compiled successfully.

4
10/26/2018 4:18:16 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