EF Core 2.2 AsNoTracking +包含引发延迟加载错误。怎么修?

我有这样的东西

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

a526399 回答:EF Core 2.2 AsNoTracking +包含引发延迟加载错误。怎么修?

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

您有两个选择:

  1. 删除AsNoTracking

  2. 忽略警告,仅将您的人际关系设为空

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

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder
        .UseLazyLoadingProxies()
        .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.DetachedLazyLoadingWarning));
}
,

您需要在项目级别的 Startup.cs 或仅针对特定操作的情况下关闭延迟加载,如下所示:

interface Model<out S : Model<S,T>,out T : View<T,S>>

interface View<out S : View<S,out T : Model<T,S>>

class RealModel : Model<RealModel,RealView>

class RealView : View<RealView,RealModel>

class Binder<T : Model<*,*>> {
    companion object {
        fun <ViewT : View<*,ModelT>,ModelT : Model<ViewT,*>> of(view: ViewT): Binder<ModelT> {
            throw RuntimeException()
        }
    }
}

一旦var result = dbContext.CompanyProducts.Include(x => x.Product).AsNotracking().ToList(); dbContext.ChangeTracker.LazyLoadingEnabled = false; var p = result.First().Product; 设置为false,您就可以按照期望的方式检查LazyLoadingEnabled是否为空。

本文链接:https://www.f2er.com/3155053.html

大家都在问