TransactionScope Error:The transaction has aborted.
This error
you may face in two conditions
1. Time out condition.
2. Inside scope other command transaction failing or rollbacks.
Solution:
Timeout Exception:
You can resolve
timeout condition issue increasing transaction scope timeout and
Ensure
timeout of the transaction scope is longer than the command timeout.
var option = new TransactionOptions
{
IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted,
Timeout = TimeSpan.FromSeconds(90)
};
myContext.CommandTimeout
= 60; //This is seconds
Inner command transaction failing:
Logical insert failing:
With following example in insert
logic what if insert store procedure has some Logic that prevents duplicate
records insertion if new records then only insert Records (if else used).
In this scenario logically insert is
not failing but command.ExecuteNonQuery will return Result 0 and command rollbacks transaction.
You can avoid this by passing output parameter and set parameter
value as continue update that will resolve your issue.
Inner exception:
Another scenario is that what if toy get exception inside scope for sub process , you can pass it to parent exception and process for next update that will
resolve your issue.
try
{
using
(TransactionScope scope = new
TransactionScope(TransactionScopeOption.RequiresNew))
{
// insert logic
try
{
using
(var conn = GetConnection())
{
string query =
@" insert Quiery"
using
(var command = new SqlCommand(query, conn))
var rowsAffected =
Command.ExecuteNonQuery();
if (rowsAffected >=
1&&ContinueUpate==1)
{
Command.Transaction.Commit();
status
= true;
}
else
{
Command.Transaction.Rollback();
}
}
}
catch
(SqlException ex)
{
// log your exception
throw; //
re-throw exception
}
// update logic
try
{
using
(var conn = GetConnection())
{
string query = @" Delete Quiery"
}
}
catch
(SqlException ex)
{
// log your exception
throw; //
re-throw exception
}
scope.Complete();
}
}
// this catch block will resolve your issue
catch
(TransactionAbortedException ex)
{
//you can log here internal exception if you want
}
When I am
trying to remove element from generic list using foreach loop, I am facing following
issue.
Error:
Collection was modified; enumeration operation may not execute.
My code:
if (duplicateUsers != null && duplicateUsers.Count()> 1)
{
foreach (var duplicateUserData in duplicateUsers)
{
UsersData.Remove(duplicateUserData);
}
}
Fix:
If you are using generic list then simply
use extension method ToList() with list i.e
duplicateUsers .ToList()
Your
code should be:
if (duplicateUsers != null && duplicateUsers.Count()> 1)
{
foreach (var duplicateUserData in duplicateUsers.ToList())
{
UsersData.Remove(duplicateUserData);
}
}