[英]Why is Entity Framework 6.1 inconsistently retrieving related entities?
我在 Entity Framework 6.1 code-first 生成的 SQL Server 数据库中有以下(子集):
然后我运行以下查询
var response = await Context.SurveyResponses
.Include(x => x.Answers)
.SingleOrDefaultAsync(x => x.Client.Id == clientId &&
x.Survey.Id == surveyId &&
!x.CompletedOn.HasValue);
在 99% 的情况下,将填充Answers
集合中的Question
对象。 然而,在 1% 的情况下,它将为空。
这个问题是通过改进Include
语句解决的,如下
var response = await Context.SurveyResponses
.Include(x => x.Answers.Select(y => y.Question))
.SingleOrDefaultAsync(x => x.Client.Id == clientId &&
x.Survey.Id == surveyId &&
!x.CompletedOn.HasValue);
但是我想了解的是为什么第一个查询有效? 它是如何知道包含Answers
对象的Question
属性的? 为什么它在某些情况下有效,而在其他情况下无效?
EF 将自动修复它可以修复的内容。 如果您的上下文已经有数据,它会为您填写。
例如,假设 id 为 1 的 SurveryResponseAnswer 有一个 id 为 1 的问题,那么:
var db=new Context();
var test=db.Questions.Where(x=>x.id==1);
var result=db.SurveyResponseAnswers.Where(x=>x.id==1);
// result's Question property is filled in
var db=new Context();
var result=db.SurveyResponseAnswers.Where(x=>x.id==1);
// result's Question property is not filled in
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.