Kashif
Kashif

Reputation: 69

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

Upvotes: 2

Views: 1994

Answers (2)

The reference Shipper is null. And not the ShipperName

Please check if (item.Shipper != null)

Upvotes: 1

smoksnes
smoksnes

Reputation: 10851

As mentioned in the answer from Ashok M. Prajapati your Shipper-property is null. But since ShipperId isn't null it means that the Shipper actually exists in the DB.

ShipperId is Foreign key which is invalid in this case.

I do not believe this is the case. Since it's not null the SQL Server will make sure that the key exists in the Shipper-table. Since a foreign key is a constraint the database will not allow you to remove an item if it has a foreign key to it. So if the foreign key is properly configured you will never have a key that doesn't point to an actual item in another table.

So what you need to do is to include it when you fetch your entity, or allow lazy loading.

1. Fetch when loading entity. By using Include you can fetch navigation-properties.

var item = context.Items.Include(x => x.Shipper).FirstOrDefault();

2. Using Lazy-loading. If you're still in the context, you can use lazy loading. Like explained in MSDN:

public class BloggingContext : DbContext 
{ 
    public BloggingContext() 
    { 
        this.Configuration.LazyLoadingEnabled = false; 
    } 
}

Upvotes: 0

Related Questions