问题
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