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; }
}
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,
};
如果ProductTypeId
在InquiryOrder
表格中有空值,则会在数组中从Object reference not set to an instance of an object
收到此错误c.ProductType.ProductTypeName
。如何调整此数组以使其接受int的空值。谢谢!
答案 0 :(得分:2)
如果ProductTypeId
为null,则表示实体框架无法延迟加载实体的产品类型,因为它不存在。
这意味着当您致电c.ProductType.ProductTypeName
c.ProductType
为空时,您在尝试获取NullReferenceException
值时获得ProductTypeName
。
你可以通过几种方式解决这个问题。如果您使用的是最新版本的C#,则可以使用Null条件运算符(?。)https://msdn.microsoft.com/en-us/library/dn986595.aspx
select new[] {
Convert.ToString(c.InquiryOrderId),
c.InquiryOrderName,
c.ProductType?.ProductTypeName,
};
如果没有,您可以使用三元运算符执行相同的功能:
select new[] {
Convert.ToString(c.InquiryOrderId),
c.InquiryOrderName,
c.ProductType != null ? c.ProductTypeProductTypeName : string.Empty,
};
答案 1 :(得分:1)
您可能想要使用三元运算符
var displayedInquiryOrders = filteredInquiryOrders.Skip(iDisplayStart).Take(iDisplayLength);
var result = from c in displayedInquiryOrders .AsEnumerable()
select new[] {
Convert.ToString(c.InquiryOrderId),
c.InquiryOrderName,
c.ProductType != null ? c.ProductType.ProductTypeName : null, //if not null, then add the product type, otherwise add null
};
在C#6.0中,我认为你可以通过?.
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
};