[英]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.