Reputation: 14417
This code:
using(var context = this.contextFactory.Create()) // creates a context
using(var transaction = context.Database.BeginTransaction()) // starts a transaction
{
try
{
await context.SaveChangesAsync(); // Save my changes
transaction.Commit(); // Commit my changes
}
catch(Exception)
{
transaction.RollBack(); // Rollback my changes
}
}
Am I correct in saying that if the transaction.Commit()
throws and error, then the transaction
will be rolled back?
Not just in the scenario of creating and entity or adding an entity to a DbSet<>
. I assume I am correct, but just want to make sure.
Upvotes: 2
Views: 1220
Reputation: 171178
A transaction either commits or rolls back. There is no in-between.
If Commit
throws it depends on the specific error what you can conclude from it. Network and timeout errors do not allow you to tell whether the transaction was committed in the store or not.
You do not need to explicitly rollback. As I said, there is no in-between. If the transaction does not commit it is certain to roll back. I don't know why so many people on the web decide to roll back explicitly. Probably, you just saw wrong sample code. The standard pattern is to do nothing in case of an error.
The error bubbles up, causes rollback and is eventually handled in a place where something can be done about it.
You are swallowing the exception. Very dangerous.
Upvotes: 6