Isuru
Isuru

Reputation: 970

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!

Upvotes: 0

Views: 63

Answers (2)

Steve
Steve

Reputation: 9571

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

Upvotes: 2

Ian
Ian

Reputation: 30813

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

Upvotes: 1

Related Questions