Linq to sql: properties of properties that may be null

A simple LINQ query:

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

Problem: CurrentLocationmay be zero. If so, executing this request causes a NullReference. I tried adding a check, for example

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

but Linq to sql doesn't seem to be able to parse it.

Any good solutions that are not related to sending an additional request for each transport?

+3
source share
3 answers

I usually use "let".

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

UPDATE:

I think that??? The operator translates to SQL.

+3
source

If the foreign key in Transports is NULL, you will need to check this column for null before you can try to get the CurrentLocation object.

- :

CurrentLocation = transport.currentLocationId != null ? transport.CurrentLocation : null;
+3

( ):

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

Update 1: This is strange, I used some rather complex queries and did not come across this problem. I just checked one, I don't think this is important, but I had a check:

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

Can you post the entire requested query that gives you a parsing exception?

+1
source

Source: https://habr.com/ru/post/1704503/


All Articles