EF4 how to wrap 2 updates in a transaction

I have two independent (unrelated) entities. Some properties of these changes change, and then I call SaveChanges. I need to wrap both updates in one transaction, as they represent the state of my application.

two updates are performed, as shown in SQL Profiler. But I do not see any transactions. Why doesn't EF4 create a transaction around two updates? How can i achieve this? (I already tried a transaction - there are still no transactions observed in Profiler)

Any ideas?

+4
source share
2 answers

This should work, but you need to do something in the correct order.

Here is some sudo code:

using (TransactionScope scope = new TransactionScope()) { //Do something with context1 //Do something with context2 //Save Changes but don't discard yet context1.SaveChanges(false); //Save Changes but don't discard yet context2.SaveChanges(false); //if we get here things are looking good. scope.Complete(); //If we get here it is save to accept all changes. context1.AcceptAllChanges(); context2.AcceptAllChanges(); } 

If you still have problems, submit your code.

+2
source

hey my records are saved even if I don’t accept all the changes

 using (TransactionScope scope = new TransactionScope()) { Roll rsr = new Roll(); rsr.RoleName = "krians"; studentEntities.Rolls.AddObject(rsr); Roll rsssddr = new Roll(); rsssddr.RoleName = "kriansss"; studentEntities1.Rolls.AddObject(rsssddr); //Do something with context1 //Do something with context2 var sdfsf = studentEntities.ObjectStateManager; //Save Changes but don't discard yet studentEntities.SaveChanges(false); var sdfssdfdsff = studentEntities.ObjectStateManager; var sdsdfdsffsf = studentEntities1.ObjectStateManager; //Save Changes but don't discard yet studentEntities1.SaveChanges(false); var sdsdfdsffsasdfasdff = studentEntities1.ObjectStateManager; //if we get here things are looking good. scope.Complete(); var sdfsf3 = studentEntities.ObjectStateManager; var sdfsfasdfasdf3 = studentEntities1.ObjectStateManager; //If we get here it is save to accept all changes. //studentEntities.AcceptAllChanges(); //studentEntities1.AcceptAllChanges(); } 
+1
source

Source: https://habr.com/ru/post/1337679/


All Articles