Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EFCore 2.0 - Include & ThenInclude : child collection -- grandchild collection [duplicate]

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)
     .ThenInclude(????????????)

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.

like image 876
Gautam T Goudar Avatar asked Jul 26 '18 20:07

Gautam T Goudar


People also ask

What is include in Entityframework?

Entity Framework Classic Include The Include method lets you add related entities to the query result. In EF Classic, the Include method no longer returns an IQueryable but instead an IncludeDbQuery that allows you to chain multiple related objects to the query result by using the AlsoInclude and ThenInclude methods.

Can I use Efcore with .NET framework?

You can use EF Core in APIs and applications that require the full . NET Framework, as well as those that target only the cross-platform .

Is Efcore an ORM?

EF Core is an object-relational mapper (ORM). Object-relational mapping is a technique that enables developers to work with data in object-oriented way by performing the work required to map between objects defined in an application's programming language and data stored in relational datasources.


1 Answers

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:

Note

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.

like image 192
Ivan Stoev Avatar answered Oct 25 '22 21:10

Ivan Stoev