tags:

views:

150

answers:

3

Simple LINQ query:

from transport in db.Transports
 select new
 {
    Current = transport.CurrentLocation,
    CurrentCarriers = transport.CurrentLocation.Carriers,
  };

Problem: CurrentLocation may be null. If it is, executing this query throws a NullReference. I tried adding a check like

transport.CurrentLocation == null ? null : transport.CurrentLocation.Carriers

but Linq to sql does not seem to be able to parse that.

Any nice solutions that do not involve sending an extra query for each transport?

+1  A: 

Just do (you where using the wrong property):

transport.CurrentLocation == null ? null : transport.CurrentLocation.Carriers

Update 1: That is weird, I have used some pretty complex queries and didn't face that issue. I just checked one, don't think it matters, but mine had the check inverted:

transport.CurrentLocation != null ? transport.CurrentLocation.Carriers : null;

Can you post the complete query you tried that gives you the parse exception?

eglasius
sorry, that was just a typo (I pasted the two parts of code from new and old versions respectively). Corrected the question.
Kurt Schelfthout
+3  A: 

I normally just use 'let'.

from x in Foo
let y = x.Bar
where y != null
select y.Baz;

UPDATE:

I think the ?? operator does translate to SQL.

leppie
+3  A: 

If the foreign key on Transports is nullable, you'll have to check that column for null before you can try and get the CurrentLocation object.

You could do something like this:

CurrentLocation = transport.currentLocationId != null ? transport.CurrentLocation : null;
ThoseDarnKids