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; } }
Entity Framework Classic ThenIncludeThe ThenInclude method moves the chaining level to the property included. It allows us to include related objects from the next level. ThenInclude is a syntactic sugar method to make it easier and clearer to include multiple related objects.
An Entity can include two types of properties: Scalar Properties and Navigation Properties. Scalar Property: The type of primitive property is called scalar properties. Each scalar property maps to a column in the database table which stores the real data.
Lazy loading means delaying the loading of related data, until you specifically request for it. When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook.
Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved by use of the Include method. For example, the queries below will load blogs and all the posts related to each blog. Include is an extension method in the System.
For EF 6
using System.Data.Entity; query.Include(x => x.Collection.Select(y => y.Property))
Make sure to add using System.Data.Entity;
to get the version of Include
that takes in a lambda.
For EF Core
Use the new method ThenInclude
query.Include(x => x.Collection) .ThenInclude(x => x.Property);
If I understand you correctly you are asking about including nested properties. If so :
.Include(x => x.ApplicationsWithOverrideGroup.NestedProp)
or
.Include("ApplicationsWithOverrideGroup.NestedProp")
or
.Include($"{nameof(ApplicationsWithOverrideGroup)}.{nameof(NestedProp)}")
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