Kashif Kashif - 1 month ago 14
ASP.NET (C#) Question

Entity Framework. Foreign key references item that doesn't exist

I am getting null object reference exception error on Export to Excel File.
Problem is that one record has foreign in database that does not have item in other table. I can't change database.

if (item.ShipperId != null)
{
str.Append("<td><font face=Arial Narrow size=" + "14px" + ">" + item.Shipper.ShipperName + "" + "</font></td>");
}
else
{
str.Append("<td><font face=Arial Narrow size=" + "14px" + ">" + "" + "</font></td>");
}
}


ShipperId is Foreign key which is invalid in this case. it gives exception on

item.Shipper.ShipperName


I have tried checking if it's null

if (item.Shipper.ShipperName != null)


but it also gives exception on this null check

Answer

The reference Shipper is null. And not the ShipperName

Please check if (item.Shipper != null)

Comments