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);
}
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.
Edit: Include() seems to be working when i do the following:
var questions = db.Questions.Include("QuestionType").Select(q => q);
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?
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).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:(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.
I ran into this issue of
Include(e => e.NavigationProperty)
not working, but the solution was different than above.The problematic code was as follows:
So the problem was the order of the code. Entity Framework appears to nullify navigation properties in memory as soon as an entity is marked as
EntityState.Deleted
. So to accessexistingUserTopic.Topic
in my code, I have to do it before markingexistingUserTopic
deleted.Here's how to do it in all types of queries. You don't need to use "Include". The only thing is that it doesn't seem like this works on many-to-many navigation properties.
Just add the navigation properties you want into the final result as "dummy" properties.
(This works with change tracking proxies. I haven't tested it in other situations. Also, don't specify ".AsNoTracking()")
Now, if you do something like this, the database won't be queried again.
Add "System.Data.Entity" and you will be able to call Include on IQueryable:
see : How can i convert a DBQuery<T> to an ObjectQuery<T>?