I am on a project using Entity Framework 6 for database access on SQL Server 2012.
We have a pending discussion in our team regarding the state of the db context after a rollback. It is quiet clear, that the database is unaffected by changes in a transaction after a rollback has been performed. But what about the context?
I am on the team that believes that the db context is rolled back as well as the database changes. In other words I take it to be safe to keep on working on the context not risking that some of the changes from the rolledback transaction still is lurking around somewhere in the context.
Can somebody kill this duck, so we can close the discussion. I have seached high and low for a clear answer without finding it.
I would be most disappointed to be wrong in my assumption, that the context is rolled back as well as the database changes. This would mean that we should stop an iteration through a set of complex updates, discard the context and start over again in case of a rollback on one of the updates.
Nothing will happen to the context
.You can use it even after the rolled back.Only the database changes will be rolled back and the DbContextTransaction
is meant to be disposed once it has been committed or rolled back.
You can use EF 6's latest transaction API as shown below.
using (var context = new YourContext())
{
using (var dbContextTransaction = context.Database.BeginTransaction())
{
try
{
//your db operations
context.SaveChanges();
dbContextTransaction.Commit();
}
catch (Exception)
{
dbContextTransaction.Rollback();
}
}
}
You can read more about it here : Entity Framework Working with Transactions