Reputation: 167
I have two independent (no relationship between) entities. Some Properties of these get changed and then I call SaveChanges. I need to wrap both updates into one transaction, since they pose a state of my application.
two updates are executed as seen in SQL Profiler. But I cannot see any transaction. Why does EF4 not create a transaction around the 2 updates? How can I achieve that? (I already tried transactionscope-still no Transaction seen in Profiler)
Any Ideas?
Upvotes: 4
Views: 269
Reputation: 11
hey my records get saved even if i dont wirte accept all 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();
}
Upvotes: 1
Reputation: 65411
This should work, but you need to do things 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 post your code.
Upvotes: 2