Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"
              select 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.

like image 385
Jeff Avatar asked Feb 21 '11 20:02

Jeff


1 Answers

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.

like image 142
Ladislav Mrnka Avatar answered Nov 10 '22 23:11

Ladislav Mrnka