A: 

.First may not be returning anything. Are you sure that the value of SomeProperty exists in SomeColumn on your dataset?

Wrap the whole thing in an if using .Any() to determine if you have a record, or test for null on the resultSet.Table2

Russell Steen
If this is the case, then it's a bug. First is supposed to throw if the sequence is empty.
Martinho Fernandes
No, as I said, all the properties of resultSet have the correct values except for Table2, which is null
BlueRaja - Danny Pflughoeft
A: 

Did you try FirstOrDefault?

Rahul Soni
yeah, didn't help
BlueRaja - Danny Pflughoeft
+5  A: 

LINQ-to-entities is simply doing something wrong.

No, it's working as designed. L2E will only JOIN in 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:

SelectedItem = _entities.Table2.First(
    o => o.Table2.SomeColumn == SomeProperty).SomeOtherColumn;  

Your lambda expression here will be interpreted by LINQ to Entities, and converted to SQL. On the other hand, this:

var resultSet =
    (from o in _entities.Table1
     where o.Table2.Table3.SomeColumn == SomeProperty
     select o
    ).First();
SelectedItem = resultSet.Table2.SomeOtherColumn;

...gives a result of type Table1. You are now in object space. Since your query does not force Table2 to be loaded, L2E won't generate SQL columns for it. This results in more efficient SQL when you don't need Table2. When you do, you have to say so:

var resultSet =
    (from o in _entities.Table1.Include("Table2")
     where o.Table2.Table3.SomeColumn == SomeProperty
     select o
    ).First();

SelectedItem = resultSet.Table2.SomeOtherColumn;

This will work. However, your First(lambda) method above is a better solution. (Compare the SQL.)

Craig Stuntz
I just realized my second query gave the *wrong* results, since Table2->Table3 is One->Many (I want the *one* used by Table1). Your `.Include()` fixed the problem, though; thanks!
BlueRaja - Danny Pflughoeft
For future googlers: see here http://msdn.microsoft.com/en-us/library/bb896272.aspx
BlueRaja - Danny Pflughoeft