C# 查询中的EF Core 2.0代码第一个错误(DetachedLazyLoadingWarning)
我的应用程序中有以下查询:C# 查询中的EF Core 2.0代码第一个错误(DetachedLazyLoadingWarning),c#,code-first,ef-core-2.0,C#,Code First,Ef Core 2.0,我的应用程序中有以下查询: 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
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();
由于我的项目是代码优先,因此会出现以下错误:
System.InvalidOperationException:'为警告'Microsoft.EntityFrameworkCore.Infrastructure.DetachedLazyLoadingWarning'生成错误:试图在类型为'ProjectProxy'的分离实体上延迟加载导航属性'ProjectLeider'。分离实体或使用“AsNoTracking()”加载的实体不支持延迟加载。通过将事件ID“CoreEventId.DetachedLazyLoadingWarning”传递给“DbContext.OnConfiguring”或“AddDbContext”中的“ConfigureWarnings”方法,可以抑制或记录此异常
到底是什么导致了这个错误?我没有使用AsNoTracking,我在查询中包含了导致错误的表。解决这个问题最简单的方法是什么
到底是什么导致了这个错误?我没有使用AsNoTracking,我在查询中包含了导致错误的表
您的查询属于以下类别:
如果更改查询,使其不再返回查询开始时的实体类型的实例,则会忽略include运算符
GroupBy
运算符正在将查询开始时的实体类型(Program
)更改为其他类型,因此.Include(i=>i.Key.ProjectLeader)
无效(被忽略)
解决此问题的最简单方法可能是直接从源查询表(项
)中删除物化和项目(选择
),例如
下面为我解决了这个问题:(使用thenclude代替Include)
不幸的是,这也不起作用。我只是在后来添加了这个,以了解错误是在代码具体化之前还是之后发生的
//var materialized = items.ToList();
return items.Select(s => new Models.Project() { ... }).ToList();
var items = Dbc.SubSubsidieProgrammas.Include(i => i.Project).ThenInclude(i => i.ProjectLeider).Where(w => w.TargetCompanyId == bedrijf.BedrijfPk).GroupBy(g => g.Project);