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.
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With