user2475096
user2475096

Reputation: 426

LINQ to entity query, check null before using navigation property

Please look at this simplified LINQ query:

var lst = from pat in ctx.PATIENTS
          join cons in ctx.CONSULTATIONS.Include(a => a.EXAMENS)
          on pat.ID_PATIENT equals cons.CON_ID_PATIENT into joinpatcons
          from p in joinpatcons.DefaultIfEmpty()
          select new ConsultationsPageType()
          {
              ID_CONSULTATION = (p == null) ? 0 : p.ID_CONSULTATION
          };

The ID_CONSULTATION field is a nullable int:

public class ConsultationsPageType
{
    //......
    public int? ID_CONSULTATION { get; set; }
    //......
}

What I want is to return null instead of zero, if p is null. Replacing simply 0 by null gave me this error:

Unable to determine the conditional expression type because there is no implicit conversion between and intentre and int

And p?.ID_CONSULTATION gave me this error:

A lambda expression arborecence can not contain a null propagation operator

I am on .NET 4.6.

Upvotes: 2

Views: 873

Answers (1)

Racil Hilan
Racil Hilan

Reputation: 25341

You can simply change the zero to null and cast it to int?:

ID_CONSULTATION = (p == null ? (int?)null : p.ID_CONSULTATION)

Upvotes: 2

Related Questions