[英]Why is Entity Framework 6.1 inconsistently retrieving related entities?
I have the following (subset) in a SQL Server database that has been generated by Entity Framework 6.1 code-first:我在 Entity Framework 6.1 code-first 生成的 SQL Server 数据库中有以下(子集):
I then run the following query然后我运行以下查询
var response = await Context.SurveyResponses
.Include(x => x.Answers)
.SingleOrDefaultAsync(x => x.Client.Id == clientId &&
x.Survey.Id == surveyId &&
!x.CompletedOn.HasValue);
In 99% of cases, the Question
object on the Answers
collection would be populated.在 99% 的情况下,将填充
Answers
集合中的Question
对象。 However in rate 1% of cases, it would be null.然而,在 1% 的情况下,它将为空。
This problem was solved by improving the Include
statement as follows这个问题是通过改进
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);
However what I'd like to understand is why the first query ever worked?但是我想了解的是为什么第一个查询有效? How did it know to include the
Question
property of the Answers
object?它是如何知道包含
Answers
对象的Question
属性的? Why did it work in some cases and not others?为什么它在某些情况下有效,而在其他情况下无效?
EF will auto-fixup what it can. EF 将自动修复它可以修复的内容。 If your context had the data already, it would fill it in for you.
如果您的上下文已经有数据,它会为您填写。
For example, assuming SurveryResponseAnswer with id of 1 has a question of id 1, then:例如,假设 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.