Entity Framework: Updating a field to a null value?
I'm using stubs to update my entities and when the updated entity consists of columns that have values changed from non-nulls to nulls, the nulls are not persisted to the database i.e. the record continues to hold the previous non-null values.
What am 开发者_开发知识库I doing wrong?
public void UpdateEntity(Entity e)
{
_context.Works.Attach(new Entity{ Id = e.Id });
_context.ApplyCurrentValues("Entities", e);
_context.SaveChanges();
}
The problem is that you need to assign null
to these properties after you Attach()
, not before. Perhaps ApplyCurrentValues()
only copies non-already-identical properties? (I've never tested, but it would be reasonable if it did.)
Try to avoid loading entities using Attach. If you just get entity from DB, you don't have to bother with settings flags on nulled items:
var stage = Db.Stages.First(s => s.ID == someId);
stage.Notation = vm.Notation; // can be also null
Db.SaveChanges();
精彩评论