EF Core 2.2 AsNoTracking + Include引发延迟加载错误。如何解决?

问题描述 投票:0回答:1

我有这样的东西

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时它为什么认为它是延迟加载?

c# ef-core-2.2
1个回答
0
投票

使用AsNoTracking方法时,延迟加载将不起作用。

您有两个选择:

  1. 删除AsNoTracking

  2. 忽略警告,只为您的人际关系提供空值

您可以配置EF忽略此错误:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder
        .UseLazyLoadingProxies()
        .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.DetachedLazyLoadingWarning));
}
© www.soinside.com 2019 - 2024. All rights reserved.