开发者

Entity Framework: Updating a field to a null value?

开发者 https://www.devze.com 2023-02-07 10:07 出处:网络
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 con

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();
0

精彩评论

暂无评论...
验证码 换一张
取 消