patterncsharpCritical
Entity Framework - Include Multiple Levels of Properties
Viewed 0 times
frameworklevelspropertiesentitymultipleinclude
Problem
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:
Will populate only the Enabled property (below) and not the Application or CustomVariableGroup properties (below). How do I make this happen?
As it stands now, this method:
public IEnumerable 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; }
}Solution
For EF 6
Make sure to add
For EF Core
Use the new method
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
ThenIncludeusing Microsoft.EntityFrameworkCore;
query.Include(x => x.Collection)
.ThenInclude(x => x.Property);Code Snippets
using System.Data.Entity;
query.Include(x => x.Collection.Select(y => y.Property))using Microsoft.EntityFrameworkCore;
query.Include(x => x.Collection)
.ThenInclude(x => x.Property);Context
Stack Overflow Q#10822656, score: 998
Revisions (0)
No revisions yet.