【问题标题】:Ef core LazyLoading - Access nested navigation property of type collection threw DetachedLazyLoadingWarning errorEf core LazyLoading - 访问集合类型的嵌套导航属性引发 DetachedLazyLoadingWarning 错误
【发布时间】:2019-07-20 01:31:37
【问题描述】:

我尝试使用 ef core 2.1 访问学生最新成绩的 GradeInfo 属性

我在问题的最后列出了模型

var students = applicationDbContext.Students.Where(s => s.Id ==2)
    .Select(student => new { 
        LatestGrade = student.Grades.OrderBy(g => g.Date).FirstOrDefault(),
        Id = student.Id
        }).ToList();

此外,我在 startup.cs 中使用延迟加载代理(来自 Microsoft.EntityFrameworkCore.Proxies)

services.AddDbContext<ApplicationDbContext>(options => 
    options.UseLazyLoadingProxies()
           .UseSqlServer(connectionString));

抛出的错误是:

“为警告 Microsoft.EntityFrameworkCore.Infrastructure.DetachedLazyLoadingWarning 生成错误:尝试在“GradeProxy”类型的分离实体上延迟加载导航属性“Info”。分离实体或实体不支持延迟加载加载了 'AsNoTracking()'。"

另外,我想声明我尝试将 Inculde 添加到学生的 dbset 中,如以下代码中所述,但问题没有解决。

var student = applicationDbContext.Students.Include( s => s.Grades )
                .ThenInclude( grade => grade.Info).Where(...).Select(...)

模型

class Student{
   public int Id { get; set;}
   public virtual ICollection<Grade> Grades { get; set;}

   ...
}

class Grade {
   public virtual GrandeInfo Info { get; set;}
   public DateTime Date { get; set;}
}

class GrandeInfo {
  public int Id { get; set;}
  public int Score { get; set;}
}

【问题讨论】:

  • 是否有任何演示可以重现您的问题?我使用 Asp.Net Core 2.2 进行了测试,但无法重现您的问题。
  • 我想澄清一下,ToList() 成功了,士兵们确实有数据作为 Id 和等级的日期,但是除了 GradeInfo 属性中的数据之外,还有一个例外。

标签: c# entity-framework linq asp.net-core .net-core


【解决方案1】:

对于这个问题,这是由于如果您更改查询使其不再返回查询开始的实体类型的实例,那么包含运算符将被忽略。你可以参考Ignored includes

并且目前不支持通过Include查询导航属性,请参考Are .Include/.ThenInclude supposed to work with Select in RC1-final? #4641

对于解决方法,您需要查询数据库中的所有列,然后在客户端查询预期的类型。

var students = _context.Students
                    .Where(s => s.Id == 2)
                    .ToList()
                    .Select(student => new
                    {
                        LatestGrade = student.Grades.OrderBy(g => g.Date).FirstOrDefault(),
                        Id = student.Id
                    })
                    .ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 2021-01-01
    • 2017-11-27
    • 2019-04-27
    相关资源
    最近更新 更多