【问题标题】:Why is Entity Framework 6.1 inconsistently retrieving related entities?为什么 Entity Framework 6.1 不一致地检索相关实体?
【发布时间】:2015-11-24 17:58:13
【问题描述】:

我在由 Entity Framework 6.1 代码优先生成的 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 属性?为什么它在某些情况下有效,而在其他情况下无效?

【问题讨论】:

    标签: c# entity-framework ef-code-first


    【解决方案1】:

    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
    

    【讨论】:

    • @peterbridger 这提出了一个有趣的观点,你的上下文应该尽可能地短暂(例如只有一个工作单元)。你在上下文中获得的项目越多,它就会越慢。
    猜你喜欢
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 2016-10-10
    • 2014-07-22
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多