简体   繁体   中英

C# TransactionScope - L2E

Is it worth using System.Transactions.TransactionScope on Linq to Entities?

On the MS documentation , it says that SQL calls within ObjectContext.SaveChanges() are all rolled into one transaction internally.

We have 1 database connection, that is a local SQLite database on the file system. We just want to make sure all our operations to the database are atomic, do we need TransactionScope? IE when we call for some deletes, updates, inserts, etc., we want them all to happen or none at all.

Jon, no you don't need to use TransactionScope. Optimistic concurrency is handled automatically by Linq. The code sample in the link you provide explains that rather well, you don't have to roll back transactions yourself. I would use the same code as in the sample:

    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");
    }

Notice the refresh, re-save, which handles your concern. You could test this out by throwing an exception from within the try block.

Best Regards

如果要在单个事务中包含多个ObjectContext.SaveChanges (例如,您要更改的数据读取以及更改),则需要使用TransactionScope

You could use the following code if you need to do what Richard says (though it seems rather unlikely):

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM