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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With