The Include() method works quite well for Lists on objects. But what if I need to go two levels deep? For example, the method below will return ApplicationServers with the included properties shown here. However, ApplicationsWithOverrideGroup is another container that holds other complex objects. Can I do an Include() on that property as well? Or how can I get that property to fully load?
As it stands now, this method:
public IEnumerable<ApplicationServer> GetAll()
{
return this.Database.ApplicationServers
.Include(x => x.ApplicationsWithOverrideGroup)
.Include(x => x.ApplicationWithGroupToForceInstallList)
.Include(x => x.CustomVariableGroups)
.ToList();
}
Will populate only the Enabled property (below) and not the Application or CustomVariableGroup properties (below). How do I make this happen?
public class ApplicationWithOverrideVariableGroup : EntityBase
{
public bool Enabled { get; set; }
public Application Application { get; set; }
public CustomVariableGroup CustomVariableGroup { get; set; }
}
I also had to use multiple includes and at 3rd level I needed multiple properties
This may help someone :)
I made a little helper for Entity Framework 6 (.Net Core style), to include sub-entities in a nice way.
It is on NuGet now : Install-Package ThenInclude.EF6
The package is available on GitHub.
For EF 6
See Remarks for more examples.
Make sure to add
using System.Data.Entity;
to get the version ofInclude
that takes in a lambda.For EF Core
Use the new method
ThenInclude
If I understand you correctly you are asking about including nested properties. If so :
or
or
EF Core: Using "ThenInclude" to load mutiple levels: For example:
More EFCore examples on MSDN show that you can do some quite complex things with
Include
andThenInclude
.This is a good example of how complex you can get (this is all one statement!):
See how you can chain
Include
even afterThenInclude
and it kind of 'resets' you back to the level of the top level entity (Instructors).You can even repeat the same 'first level' collection (CourseAssignments) multiple times followed by separate
ThenIncludes
commands to get to different child entities.Note your actual query must be tagged onto the end of the
Include
orThenIncludes
chain. The following does NOT work:Would strongly recommend you set up logging and make sure your queries aren't out of control if you're including more than one or two things. It's important to see how it actually works - and you'll notice each separate 'include' is typically a new query to avoid massive joins returning redundant data.
AsNoTracking
can greatly speed things up if you're not intending on actually editing the entities and resaving.