.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
.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
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.)