EFCore 2.0 - Include & ThenInclude : child collection -- grandchild collection

c# entity-framework-core


For a model like below

public class Parent
    public int Id { get; set; }

    public List<Child> Children { get; set; }

public class Child
    public int ChildId { get; set; }

    public int ParentId { get; set; }

    public List<Child> GrandChildren { get; set; }

public class GrandChild
    public int GrandChildId { get; set; }

    public int ChildId { get; set; }

How do I write a query that gets all the Children and GrandChildren in the Include/ThenInclude statements?

var record = GetAll()
 .Where(r => r.Id == 4)
 .Include(r => r.Children)

In the "ThenInclude" statement, I cannot use a select statement to get the grandchildren. What will be the right way to get the GrandChildren collection?

Much appreciated.

7/26/2018 9:19:27 PM

Accepted Answer

Just type the navigation property name:

.ThenInclude(c => c.GrandChildren)

It's a current Intellisense issue specifically mentioned in the Including multiple levels section of the EF Core documentation:


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.

7/26/2018 9:04:47 PM

Related Questions


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