接受int的空值的匿名数组

时间:2016-01-18 04:11:42

标签: c# linq anonymous-arrays

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

如果ProductTypeIdInquiryOrder表格中有空值,则会在数组中从Object reference not set to an instance of an object收到此错误c.ProductType.ProductTypeName。如何调整此数组以使其接受int的空值。谢谢!

2 个答案:

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