Cannot set bool value to false in entity framework update method

柔情痞子 提交于 2020-04-18 05:57:32

问题


I got strange problem when I try to update existing entity.

public void Update(VisitDTO item)
        {
            using (var ctx = new ReceptionDbContext())
            {
                var entityToUpdate = ctx.Visits.Attach(new Visit { Id = item.Id });
                var updatedEntity = Mapper.Map<Visit>(item);
                ctx.Entry(entityToUpdate).CurrentValues.SetValues(updatedEntity);
                ctx.SaveChanges();

            }

This is my update method. In enity Visit I got some bools values, but i cannot set these to false , when it comes to update from false to true its okay but when I need to change from true to false entity does not update these bools values, other properties updating correctly.


回答1:


The problem is that default(bool) == false.

 var entityToUpdate = ctx.Visits.Attach(new Visit { Id = item.Id });

is the same as

 var entityToUpdate = ctx.Visits.Attach(new Visit 
 { 
     Id = item.Id, 
     AnyBool = false        // default(bool)
 });

Attach sets all fields to the UNCHANGED state.

EntityFramework assumes that the new Visit object contains the correct values (even though it does not). Updating AnyBool to false is ignored, because EF thinks it already is false!

You need to manually change the status to MODIFIED for fields which are to be modified:

ctx.Entry(entityToUpdate).State = EntityState.Modified;                 // all fields
ctx.Entry(entityToUpdate).Property(x => x.AnyBool).IsModified = true;   // one field

See How to update only one field in Entity Framework?



来源:https://stackoverflow.com/questions/48300591/cannot-set-bool-value-to-false-in-entity-framework-update-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!