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.
精彩评论