编程语言
首页 > 编程语言> > c#-Ef核心LazyLoading-类型集合的访问嵌套导航属性引发DetachedLazyLoadingWarning错误

c#-Ef核心LazyLoading-类型集合的访问嵌套导航属性引发DetachedLazyLoadingWarning错误

作者:互联网

我尝试使用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));

引发的错误是:

“Error generated for warning Microsoft.EntityFrameworkCore.Infrastructure.DetachedLazyLoadingWarning: An attempt was made to lazy-load navigation property ‘Info’ on detached entity of type ‘GradeProxy’. Lazy-Loading is not supported for detached entities or entities that are loaded with ‘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;}
}

解决方法:

对于此问题,其原因是,如果更改查询以使其不再返回查询开始的实体类型的实例,则会忽略包含运算符.您可以参考Ignored includes

.

并且,当前不支持通过“包含”查询导航属性,请参见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();

标签:asp-net-core,net-core,linq,c,entity-framework
来源: https://codeday.me/bug/20191211/2106069.html