Expert wanna be
Expert wanna be

Reputation: 10624

how to check Object Reference?

I have like this entity,

public class Receiving{
  [Key]
  public int ID {get; set;}
  public string shipperID {get; set;}

  [Foregign("shipperID")]
  public virtual Shipper shipper {get; set;}
}

the Shipper relationship could be 1:0 or 1:1

and I got an error when the shipper is 0.

var result = from p in productRepository
             join o in receivingRepository
             on p.fk equals o.ID
             select new {
               test = o.shipper.name // if the shipper is nothing related then it occur an error.
             }

The error message say, "Object reference not set to an instance of an object."

How can I check that in select {}?

I tried,

select new {
  test = o.shipper.name ?? ""
}

but it is not working.

Upvotes: 1

Views: 299

Answers (1)

Andrew Kennan
Andrew Kennan

Reputation: 14157

Try (o == null || o.shipper == null) ? "" : o.shipper.name

Upvotes: 3

Related Questions