Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 839
jallen Avatar asked Jun 07 '12 15:06

jallen


1 Answers

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();
}
like image 55
Slauma Avatar answered Sep 28 '22 03:09

Slauma