开发者

AcceptAllChanges causes Entity Framework to ... not accept the changes?

开发者 https://www.devze.com 2023-02-12 05:11 出处:网络
I\'m using .NET 3.5 SP1. I have a simple script that deletes some entities. var people = (from Person p in context.People

I'm using .NET 3.5 SP1. I have a simple script that deletes some entities.

var people = (from Person p in context.People
              where p.FirstName == "Testy" && 
                    p.LastName == "McTesterson"
              sele开发者_如何转开发ct p).ToList();
people.ForEach(p => context.DeleteObject(p));

//context.AcceptAllChanges();
context.SaveChanges();

If I uncomment AcceptAllChanges(), the objects are not deleted. If I keep it commented, the entities are deleted. Why does EF behave like this? It seems counter productive.


That is the behavior of AcceptAllChanges. Accepting changes "resets" the internal state of ObjectContext. It means that all entities which were added or modified are set to "unchanged" state and all entities which were deleted are detached from the context.

In contrast, SaveChanges method iterates the internal state of ObjectContext and creates INSERT db commands for each entity with a state of added, UPDATE db command for each entity in modified state and DELETE db command for each entity in deleted state. SaveChanges by default accepts all changes after it executes all commands.

If you run AcceptAllChanges before SaveChanges you clear all changes and there is nothing to execute in DB. The reason why this method exists is that you can turn off default SaveChanges behavior; in such a case, you must accept changes manually after you execute SaveChanges. Otherwise the next call to SaveChanges will execute the changes again.

0

精彩评论

暂无评论...
验证码 换一张
取 消