代码之家  ›  专栏  ›  技术社区  ›  chobo2

efcore2.2asnotracking+Include抛出一个懒加载错误。如何修复?

  •  0
  • chobo2  · 技术社区  · 5 年前

    我有这样的东西

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

    1 回复  |  直到 5 年前
        1
  •  0
  •   MasLoo    5 年前

    AsNoTracking 方法。

    1. 删除

    2. 忽略警告,只需为您的关系设置null

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder
            .UseLazyLoadingProxies()
            .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.DetachedLazyLoadingWarning));
    }
    
        2
  •  0
  •   Daniel Congrove    4 年前

    您需要在中的项目级别关闭延迟加载 启动.cs

    var result = dbContext.CompanyProducts.Include(x => x.Product).AsNotracking().ToList();
    dbContext.ChangeTracker.LazyLoadingEnabled = false;
    
    var p = result.First().Product;
    

    一次 LazyLoadingEnabled 设置为false,则可以检查 Product

    推荐文章