I'm trying to update a record using EntityFramework 6 by attaching a disconnected entity. I want to update a single boolean field to false but it doesn't work. I have used sql server profiler and EF doesn't generate an update statement when calling SaveChanges on the context. But if i set the value to true, it works. Example:
This doesn't work:
private void UpdateUser()
{
var user = new User { ID = 5 };
this.Context.Users.Attach(user);
user.Locked = false;
this.Context.SaveChanges();
}
This works:
private void UpdateUser()
{
var user = new User { ID = 5 };
this.Context.Users.Attach(user);
user.Locked = true;
this.Context.SaveChanges();
}
I can fix by marking the property as modified like this:
this.Context.Entry(user).Property(e => e.Locked).IsModified = true;
But don't understand why does it work if the value is true and not if the value is false. There is a similar issue when trying to set a field to null.
There's probably something wrong with the entity data model or database but can't figure out what.
Default value for Boolean is false, so setting to false after attaching won't flag the property as changed.
You can load the entity first, then do your modifications then save changes.
var user = db.Users.Find(5);
user.Locked = false;
db.SaveChanges();
Or you can attach the entity with the field you want to update set to a different value for Boolean fields
var user = new User { Id = 5, Locked = true; };
db.Users.Attach(user);
user.Locked = false;
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