简体   繁体   中英

LINQ-to-entities - Null reference

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.

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

.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM