'对象引用未设置为对象的实例'来自匿名数组的错误

时间:2016-01-14 12:00:51

标签: c# linq asp.net-mvc-5

InquiryOrder Model

public class InquiryOrder
{
    [Key]
    public int InquiryOrderId { get; set; }

    public string InquiryOrderName { get; set; }

    [ForeignKey("ProductType")]
    public int? ProductTypeId { get; set; }
    public virtual ProductType ProductType { get; set; }
}

ProductType Model

public class ProductType
{
    [Key]
    public int ProductId { get; set; }

    [StringLength(100, ErrorMessage = "Must be less than 100 charcters", MinimumLength = 1)]
    [Required(ErrorMessage = "Required")]
    public string ProductTypeName { get; set; }

    public virtual List<InquiryOrder> inquiryOrders { get; set; }
}

InquiryOrder控制器

var displayedInquiryOrders = filteredInquiryOrders.Skip(iDisplayStart).Take(iDisplayLength);
        var result = from c in displayedInquiryOrders .AsEnumerable()
                      select new[] { 
                                Convert.ToString(c.InquiryOrderId),
                                c.InquiryOrderName,
                                c.ProductType.ProductTypeName,
                            };

此处来自c.ProductType.ProductTypeName,即时收到此错误Object reference not set to an instance of an object。请帮我解决这个问题。谢谢!

2 个答案:

答案 0 :(得分:3)

下面

new[] { 
                            Convert.ToString(c.InquiryOrderId),
                            c.InquiryOrderName,
                            c.ProductType.ProductTypeName,
                        };

或者:

  • c为空
  • c.ProductType为空

答案 1 :(得分:0)

您需要添加一些NullReference控件。请试试这个:

           select new[]{ 
                            Convert.ToString(c?.InquiryOrderId),
                            c?.InquiryOrderName,
                            c?.ProductType?.ProductTypeName,
                        };