0

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.

Asvv
  • 44
  • 1
  • 5
  • what is the error or exception you are getting ? – sifa vahora Jan 17 '18 at 11:58
  • I dont get any error, Its updating correctly but update dont affects bools values when they are set to true and its need to be changed to false – Asvv Jan 17 '18 at 12:00
  • You need to debug and check what values does `entityToUpdate` and `updatedEntity` has when it tries to update. – Just code Jan 17 '18 at 12:01
  • I 'using' block all values are set corrently, in 'updatedEntity' and 'entityToUpdate' but when I open new 'using' block after first bools are set incorrectly. – Asvv Jan 17 '18 at 12:04
  • Why is your method called `Update` while at the same time you **add a new entry** to the Context? This does not make sense. See [this answer](https://stackoverflow.com/a/36684660/1220550) for how to do it properly. – Peter B Jan 17 '18 at 12:04
  • I dont really understand what do you mean, this funtion updating correctly all values in entity expect update bools from true to false – Asvv Jan 17 '18 at 12:07
  • oh, now I understand your meaning I got huge misunderstanding to Attach method and this is my struggling problem, when I changed Attach to 'ctx.Visits.Where(x=>x.id == item.Id);' It seems to work properly. – Asvv Jan 17 '18 at 12:13

1 Answers1

3

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?