简体   繁体   中英

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:

数据库模式

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. However in rate 1% of cases, it would be null.

This problem was solved by improving the Include statement as follows

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? Why did it work in some cases and not others?

EF will auto-fixup what it can. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM