【问题标题】:What is the right way to use TransactionScopes with MVC4?将 TransactionScopes 与 MVC4 一起使用的正确方法是什么?
【发布时间】:2013-09-12 19:34:59
【问题描述】:

我为每个请求使用一个 TransactionScope,如下所示:

public ActionResult Login(string user, string pass)
{
    using (ServerContext context = new ServerContext ())
    {
        TransactionOptions transOptions = new TransactionOptions();
        transOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
        transOptions.Timeout = TransactionManager.MaximumTimeout;

        using (var scope = new TransactionScope(TransactionScopeOption.Required, transOptions))
        {
           // Some logic and Linq queries here
        }
}

我在事务范围内执行了一些插入、更新、删除和过程调用 但是,我遇到了一些罕见的高负载死锁异常。所以,我做得对吗? 还是最好为每个操作打开一个 TransactionScope? (但如果其中一个集合失败,我需要回滚所有操作。)

谢谢。

【问题讨论】:

  • 一般来说,这是正确的。您是否真的在 SQL Server 中死锁,或者您的意思是阻塞导致请求超时?
  • 只有当您有多个应该是事务性的 SaveChanges 调用时,您才需要一个 TS。我猜你就是这么做的?

标签: c# asp.net-mvc-4 entity-framework-5


【解决方案1】:

AFAIK,在 L2S 中调用 SubmitChanges 时,LINQ to SQL 会检查调用是否在事务范围内,或者事务属性 (IDbTransaction) 是否设置为用户启动的本地事务。如果未找到任何事务,LINQ to SQL 将启动一个本地事务 (IDbTransaction) 并使用它来执行生成的 SQL 命令。当所有 SQL 命令都成功完成后,LINQ to SQL 提交本地事务并返回。

我对 MVC/EF 没有任何想法,但尝试像这样包装:

 using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew))
 {
     using (ServerContext context = new ServerContext ())
     {


           // Some logic and Linq queries here
     }
     scope.Complete();
 }

【讨论】:

    猜你喜欢
    • 2018-04-10
    • 2013-01-02
    • 1970-01-01
    • 2020-08-27
    • 2020-07-10
    • 2020-09-29
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多