我有这样的东西
var result = dbContext.CompanyProducts.Include(x => x.Product).AsNotracking().Where(//some condtions).GroupBy(x => x.id).ToList()
var p = result.First().Product但我得到了
"Error generated for warning 'Microsoft.EntityFrameworkCore.Infrastructure.DetachedLazyLoadingWarning:
An attempt was made to lazy-load navigation property 'Product' on detached entity of type 'CompanyProductProxy'.
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'."}当我使用include时,为什么它认为它是延迟加载?
发布于 2019-11-06 12:07:14
使用AsNoTracking方法时,延迟加载将不起作用。
您有两个选择:
删除警告,并简单地为
获取null
您可以配置EF忽略此错误:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseLazyLoadingProxies()
.ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.DetachedLazyLoadingWarning));
}发布于 2020-03-14 03:59:01
您需要在Startup.cs中的项目级别或仅针对特定操作关闭延迟加载,如下所示:
var result = dbContext.CompanyProducts.Include(x => x.Product).AsNotracking().ToList();
dbContext.ChangeTracker.LazyLoadingEnabled = false;
var p = result.First().Product;一旦LazyLoadingEnabled设置为false,您就可以像预期的那样检查Product是否为null。
https://stackoverflow.com/questions/58722889
复制相似问题