C # TransactionScope - L2E

Should I use System.Transactions.TransactionScope for Linq for objects?

The MS documentation says that SQL calls in ObjectContext.SaveChanges () are completely flipped into a single transaction.

We have 1 database connection, that is, a local SQLite database in the file system. We just want to make sure that all our database operations are atomic, do we need a TransactionScope? I.E. when we cause some deletions, updates, inserts, etc., we want them all to happen or not to happen at all.

+5
source share
3 answers

, , TransactionScope. concurrency Linq. , , . , :

    try
    {
        // Try to save changes, which may cause a conflict.
        int num = context.SaveChanges();
        Console.WriteLine("No conflicts. " +
            num.ToString() + " updates saved.");
    }
    catch (OptimisticConcurrencyException)
    {
        // Resolve the concurrency conflict by refreshing the 
        // object context before re-saving changes. 
        context.Refresh(RefreshMode.ClientWins, orders);

        // Save changes.
        context.SaveChanges();
        Console.WriteLine("OptimisticConcurrencyException "
        + "handled and changes saved");
    }

, , . , try.

+3

ObjectContext.SaveChanges (, , , ), TransactionScope.

+1

, , ( ):

TransactionManager transactionManager = null;

try
{
    bool isBorrowedTransaction = ConnectionScope.Current.HasTransaction;
    transactionManager = ConnectionScope.ValidateOrCreateTransaction(true);

    //MANY SAVES

    if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen)
        transactionManager.Commit();
}
catch (Exception ex)
{
    if (transactionManager != null && transactionManager.IsOpen)
        transactionManager.Rollback();
    log.Error("An unexpected Exception occurred", ex);
    throw;
}
0

All Articles