Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 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 Reply

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...