在实体框架更新方法中无法将bool值设置为false

在实体框架更新方法中无法将bool值设置为false

本文介绍了在实体框架更新方法中无法将bool值设置为false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试更新现有实体时遇到一个奇怪的问题.

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

            }

这是我的更新方法.在enity Visit中,我得到了一些bool值,但是我无法将它们设置为false,当从false更新为true时还可以,但是当我需要从true更改为false时,实体不会更新这些bool值,其他属性也会正确更新

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.

推荐答案

问题是default(bool)== false.

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

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

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

附加集所有字段都变为UNCHANGED状态.

Attach sets all fields to the UNCHANGED state.

EntityFramework假定新的Visit对象包含正确的值(即使不是).将EF更新为false会被忽略,因为EF认为它已经为假!

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

请参见如何仅更新实体框架中的一个字段?

这篇关于在实体框架更新方法中无法将bool值设置为false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 14:40