gpt4 book ai didi

c# - EF Core 2.0 Code First 查询错误 (DetachedLazyLoadingWarning)

转载 作者:行者123 更新时间:2023-11-30 21:31:12 26 4
gpt4 key购买 nike

我的应用程序中有以下查询:

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: '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'.'

究竟是什么导致了这个错误?我没有使用 AsNoTracking,我在查询中包含了导致错误的表。解决这个问题最简单的方法是什么?

最佳答案

What is exactly causing this error? I am not using AsNoTracking and I included that table that is causing the error in the query.

您的查询属于Ignored Includes类别:

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.

GroupBy 运算符正在将查询以 (Program) 开头的实体类型更改为其他内容,因此 .Include(i => i.Key. ProjectLeader) 无效(被忽略)。

可能最简单的解决方法是直接从可查询的源(items)中删除具体化和项目(Select),例如

//var materialized = items.ToList();
return items.Select(s => new Models.Project() { ... }).ToList();

关于c# - EF Core 2.0 Code First 查询错误 (DetachedLazyLoadingWarning),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53539922/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com