0

询价订单型号

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; }
}

查询订单控制器

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获取此错误。如何调整此数组以使其接受 int 的空值。谢谢!Object reference not set to an instance of an objectc.ProductType.ProductTypeName

4

2 回答 2

2

如果ProductTypeId为 null,则意味着实体框架不能延迟加载实体的产品类型,因为它不存在。

这意味着当您调用时c.ProductType.ProductTypeName c.ProductType为 null 并且您NullReferenceException在尝试获取ProductTypeName值时得到 a 。

您可以通过多种方式解决此问题。如果您使用的是最新版本的 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,
};
于 2016-01-18T04:15:21.867 回答
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
                    };
于 2016-01-18T04:15:06.207 回答