我有这样的
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时,为什么它认为它是懒惰加载?
使用AsNoTracking
方法时,延迟加载将不起作用。
你有两个选择:
-
删除
AsNoTracking
-
忽略警告,只需为您的关系获取null
您可以将EF配置为忽略此错误:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseLazyLoadingProxies()
.ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.DetachedLazyLoadingWarning));
}
您需要关闭延迟加载,无论是在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。