Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

c# - Cannot set bool value to false in entity framework update method

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...