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
  • Did you mean to say transport.CurrentLocation or transport.Current? Commented Mar 10, 2009 at 15:52

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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;

Comments

1

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?

1 Comment

sorry, that was just a typo (I pasted the two parts of code from new and old versions respectively). Corrected the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.