Reputation: 780
I have the following query in my application:
var Company = Db.Company.SingleOrDefault(si => si.Guid == companyId);
var items = Db.Programs.Where(w => w.SubCompanyId == Company.CompanyId)
.GroupBy(g => g.Projects).Include(i => i.Key.ProjectLeader);
if (skip.HasValue && take.HasValue)
{
items = items.OrderByDescending(o => o.Key.DatumAanmaak).Skip(skip.Value).Take(take.Value);
}
var materialized = items.ToList();
return materialized.Select(s => new Models.Project()
{
Guid = s.Key.Guid,
ProjectId = s.Key.Id,
Title = s.Key.Titel,
CompanyId= s.Key.CompanyId,
ProjectLeaderFk = s.Key.ProjectLeaderId,
ProjectLeaderName = s.Key.ProjectLeader.FullName,
IsIncoming = s.Key.IsIncoming ?? true,
ProgramCount = s.Count(w => w.TargetCompanyId == Company.CompanyId),
ApplicationAmount = s.Where(w => w.TargetCompanyId == Company.CompanyId).Sum(su => su.ApplicationAmount ),
AvailableAmount = s.Where(w => w.TargetCompanyId == Company.CompanyId).Sum(su => su.AvailableAmount)
}).ToList();
Since my project is code first, this gives the following error:
System.InvalidOperationException: 'Error generated for warning 'Microsoft.EntityFrameworkCore.Infrastructure.DetachedLazyLoadingWarning: An attempt was made to lazy-load navigation property 'ProjectLeider' on detached entity of type 'ProjectProxy'. Lazy-loading is not supported for detached entities or entities that are loaded with 'AsNoTracking()'.'. This exception can be suppressed or logged by passing event ID 'CoreEventId.DetachedLazyLoadingWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.'
What is exactly causing this error? I am not using AsNoTracking and I included that table that is causing the error in the query. What is the easiest way to solve this?
Upvotes: 1
Views: 121
Reputation: 780
The following solved it for me: (using ThenInclude instead of Include)
var items = Dbc.SubSubsidieProgrammas.Include(i => i.Project).ThenInclude(i => i.ProjectLeider).Where(w => w.TargetCompanyId == bedrijf.BedrijfPk).GroupBy(g => g.Project);
Upvotes: 0
Reputation: 205729
What is exactly causing this error? I am not using AsNoTracking and I included that table that is causing the error in the query.
Your query is falling into Ignored Includes category:
If you change the query so that it no longer returns instances of the entity type that the query began with, then the include operators are ignored.
The GroupBy
operator is changing the entity type the query began with (Program
) to something else, so .Include(i => i.Key.ProjectLeader)
has no effect (is ignored).
Probably the easiest way to resolve it is to remove the materialization and project (Select
) directly from the source queryable (items
), e.g.
//var materialized = items.ToList();
return items.Select(s => new Models.Project() { ... }).ToList();
Upvotes: 2