实体框架 Include() 不起作用 [英] Entity Framework Include() is not working

查看:78
本文介绍了实体框架 Include() 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 EF 查询:

I have the following EF query:

TestEntities db = new TestEntities();
var questions = from q in db.Questions.Include("QuestionType")
                from sq in db.SurveyQuestions
                where sq.Survey == surveyTypeID
                orderby sq.Order
                select q;

foreach( var question in questions ) {
    // ERROR: Null Reference Exception
    Console.WriteLine("Question Type: " + question.QuestionType.Description);
}

我在访问 QuestionType 属性时收到空引用异常.我正在使用 Include("QuestionType") 但它似乎不起作用.我做错了什么?

I am getting a null reference exception when I access the QuestionType property. I am using Include("QuestionType") but it doesn't appear to be working. What am I doing wrong?

编辑:当我打开延迟加载时,它不会抛出空引用异常.

Edit: It does not throw a null reference exception when I have Lazy Loading turned on.

编辑:当我执行以下操作时,Include() 似乎正在工作:

Edit: Include() seems to be working when i do the following:

var questions = db.Questions.Include("QuestionType").Select(q => q);

当我断言一个单独的实体时 Include 似乎失败了.使用 Include 时不允许这样做吗?我的查询导致这件事不起作用怎么办?

When I predicate on a separate entity Include seems to fail. Is that not allowed when using Include? What about my query is causing this thing to not work?

推荐答案

问题可能与 Linq 表达式中的子查询有关.子选择、分组和投影可能导致使用 Include 进行预加载以静默方式失败,如上所述 此处并详细解释此处(在线程中间某处查看 Diego Vega 的答案).

The problem might be related to the subquery in your Linq expression. Subselects, grouping und projections can cause eager loading with Include to fail silently, as mentioned here and explained in more detail here (see answers of Diego Vega somewhere in the middle of the thread).

虽然我看不出您在使用那些帖子中描述的 Include 时违反了任何要遵循的规则,但您可以尝试根据建议更改查询:

Although I cannot really see that you violate any of the rules to follow when using Include as described in those posts, you could try to change the query according to the recommendation:

var questions = from q in db.Questions
                from sq in db.SurveyQuestions
                where sq.Survey == surveyTypeID
                orderby sq.Order
                select q;

var questionsWithInclude = ((ObjectQuery)questions).Include("QuestionType");

foreach( var question in questionsWithInclude ) {
    Console.WriteLine("Question Type: " + question.QuestionType.Description);
}

(或者使用帖子中提到的扩展方法.)

(Or use the extension method mentioned in the posts.)

如果我正确理解链接的帖子,这并不一定意味着它现在会起作用(可能不会),但是您会收到一个异常,为您提供有关问题的更多详细信息.

If I understand the linked posts correctly, this does not necessarily mean that it will work now (probably not), but you will get an exception giving you more details about the problem.

这篇关于实体框架 Include() 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆