如何检查对象参考?

时间:2012-11-07 03:29:13

标签: c#

我喜欢这个实体,

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

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

托运人关系可以是 1:0或1:1

当托运人为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.
             }

错误消息说, “对象引用未设置为对象的实例。”

如何在select {}?

中查看

我试过了,

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

但它不起作用。

1 个答案:

答案 0 :(得分:3)

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