【发布时间】: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