0

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!

Isuru
  • 950
  • 1
  • 13
  • 34

2 Answers2

2

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,
};
Steve
  • 9,335
  • 10
  • 49
  • 81
1

You may want to use ternary operator

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

In C#6.0, I think you could do it by ?.

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
                    };
Ian
  • 30,182
  • 19
  • 69
  • 107
  • Yes this works. Since `Steve` put the answer first i marked it. But thanks a lot for helping me.. – Isuru Jan 18 '16 at 04:46