Search code examples
c#linqanonymous-arrays

Anonymous array accepting null values for int


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 Controller

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

if ProductTypeId has null values in InquiryOrder table im getting this error Object reference not set to an instance of an object from c.ProductType.ProductTypeName in array. How to adjust this array such that it accepts null values for int. Thanks!


Solution

  • If ProductTypeId is null, that means that Entity Framework can't lazy load the Product Type for the entity, since it doesn't exist.

    That means when you call c.ProductType.ProductTypeName c.ProductType is null and you get a NullReferenceException when trying to get the ProductTypeName value.

    You can fix this a couple of ways. If you are using the latest version of C# you can use the Null-conditional operator (?.) https://msdn.microsoft.com/en-us/library/dn986595.aspx

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

    If not, you can use a ternary operator to perform the same function:

    select new[] { 
        Convert.ToString(c.InquiryOrderId),
        c.InquiryOrderName,
        c.ProductType != null ? c.ProductTypeProductTypeName : string.Empty,
    };