简体   繁体   English

C#TransactionScope - L2E

[英]C# TransactionScope - L2E

Is it worth using System.Transactions.TransactionScope on Linq to Entities? 在Linq to Entities上使用System.Transactions.TransactionScope是否值得?

On the MS documentation , it says that SQL calls within ObjectContext.SaveChanges() are all rolled into one transaction internally. MS文档中 ,它说ObjectContext.SaveChanges()中的SQL调用都在内部集成到一个事务中。

We have 1 database connection, that is a local SQLite database on the file system. 我们有1个数据库连接,即文件系统上的本地SQLite数据库。 We just want to make sure all our operations to the database are atomic, do we need TransactionScope? 我们只是想确保我们对数据库的所有操作都是原子的,我们需要TransactionScope吗? IE when we call for some deletes, updates, inserts, etc., we want them all to happen or none at all. IE当我们调用一些删除,更新,插入等时,我们希望它们全部发生或根本不发生。

Jon, no you don't need to use TransactionScope. Jon,不,你不需要使用TransactionScope。 Optimistic concurrency is handled automatically by Linq. 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. 您可以通过从try块中抛出异常来测试它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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