We have a scenario to save two entities from two contexts in single transaction.
Step 1 – SetTransaction(firstContext, true);
Step 2 – Save first entity using firstContext.
Step 3 – SetTransaction(secondContext, false);
Step 4 – Save second entity using secondContext
Step 5 – finally commit the transaction.
void function SetTransaction(context, startNewTransaction)
{
var currentContext = firstContext;
if (startNewTransaction)
{
var connection = currentContext.GetConnection();
connection.Open();
this.dbTransaction = connection.BeginTransaction();
}
if (this.dbTransaction != null)
{
currentContext.UseTransaction(dbTransaction);
}
}
While executing Step 3, currentContext.UseTransaction(dbTransaction); line throws the exception as "The transaction passed in is not associated with the current connection. Only transactions associated with the current connection may be used"
Please suggest how to resolve.
Venkat.
Best Solution
Use the
TransactionScope
. EF will automatically enlist in a running transaction-scope.It will require that your connectionstrings are identical.