I could swear this was working the other day:
var resultSet =
(from o in _entities.Table1
where o.Table2.Table3.SomeColumn == SomeProperty
select o
).First();
SelectedItem = resultSet.Table2.SomeOtherColumn;
I am getting a null reference exception on the last line: resultSet.Table2 is null.
Not only am I sure that all the foreign keys and whatnot have the correct values, but I don’t see how Table2 could be null, since o.Table2.Table3.SomeColumn == SomeProperty.
resultSet has all the correct values, with the exception that Table2 is null.
[Edit] This works:
SelectedItem = _entities.Table2.First(
o => o.Table2.SomeColumn == SomeProperty).SomeOtherColumn;
And, above, resultSet has all the correct values, so it is not a problem with the data in the database; LINQ-to-entities is simply doing something wrong.
No, it’s working as designed. L2E will only
JOINin tables when you force it to. This improves performance. As long as you are in L2E, you can reference any relationship. That’s why this works:Your lambda expression here will be interpreted by LINQ to Entities, and converted to SQL. On the other hand, this:
…gives a result of type
Table1. You are now in object space. Since your query does not forceTable2to be loaded, L2E won’t generate SQL columns for it. This results in more efficient SQL when you don’t needTable2. When you do, you have to say so:This will work. However, your
First(lambda)method above is a better solution. (Compare the SQL.)