jallen
jallen

Reputation: 612

Entity Framework will not update foreign key value to null

I cannot get the foreign key in my Entity Framework 4.3 code first database to be updated to null.

My view model:

public class AccountViewModel
{
    public int Id { get; set; }
    public int? CorporationId { get; set; } 
    public CorporationModel Corporation { get; set; }
}

var corporation = db.Corporation.Where(x => x.Id == model.CorporationId).FirstOrDefault();  // shows as null
account.Corporation = corporation;  // sets the value to null

db.Entry(account).State = EntityState.Modified;
db.SaveChanges();  // does not save the null value in the FK field!!!

Any assistance would be GREATLY appreciated.

Upvotes: 7

Views: 8508

Answers (1)

Slauma
Slauma

Reputation: 177133

You must set the foreign key property to null. Setting the state to Modified only affects scalar properties (and the foreign key property is one of them but not the navigation property):

account.CorporationId = null;

db.Entry(account).State = EntityState.Modified;
db.SaveChanges();

If you don't have a foreign key property on Account you must load the account including the corporation:

var account = db.Account.Include(a => a.Corporation)
    .Where(a => a.Id == accountId)
    .SingleOrDefault();

if (account != null)
{
    account.Corporation = null;
    db.SaveChanges();
}

Upvotes: 13

Related Questions