【问题标题】:Sql transaction is complete exceptionsql事务完成异常
【发布时间】:2014-09-29 11:58:21
【问题描述】:

我有一个奇怪的问题。所有文档都指出必须在提交事务之前首先调用 SaveChanges() 方法,但在我的情况下,如果这样做会引发异常。 通过在SaveChanges() 之前调用 Commit 可以避免“Sql 事务完成异常”

    [HttpPost]
    public ActionResult ajax_SaveScreentest(string ScreenTestResult = "")
    {

        var shops = from m in db_emp.WorkLocations
                    where m.LocationType == "Shop"
                    select m;       

        db.Database.Connection.Open();
        using (var dbtran = db.Database.Connection.BeginTransaction())
        {
            try
            {
                if (ScreenTestResult != "")
                {

                    var sc = js.Deserialize<ScreenTest>(ScreenTestResult);
                    AppFieldValidator.Validate(sc);
                    db.Entry(sc).State = System.Data.EntityState.Added;
                    dbtran.Commit(); //needs to commit first before savechanges otherwise The sql                transaction is completed exception will occur
                    db.SaveChanges();


                    foreach (var obj in shops)
                    {
                        ScreenShop ss = new ScreenShop();
                        ss.ScreenID = sc.ID;
                        ss.ShopID = obj.WorkLocationID;
                        ss.ScreenStatus = "Outstanding";
                        ss.ScreenDateSubmitted = null;
                        db.Entry(ss).State = System.Data.EntityState.Added;
                    }

                    db.SaveChanges();

                    return Json(new { success = true, message = "" });
                }
                return Json(new { success = false, message = "Screen Test is not supplied" });
            }

            catch (Exception e)
            {
                dbtran.Rollback();
                if (e.Message.IndexOf("Validation failed for one or more entities.") != -1)
                    return Json(new { success = false, message = "One of the entries you made is      ether too long or unacceptable!" });
                return Json(new { success = false, message = e.InnerException != null ?    e.InnerException.Message : e.Message });
            }
            finally
            {
                db.Dispose();
            }
        }

【问题讨论】:

    标签: asp.net-mvc json linq transactions entity-framework-5


    【解决方案1】:

    nvm 解决了这个错误我首先在调用 Commit 之前添加了 db.SaveChanges() 方法

    【讨论】:

      猜你喜欢
      • 2020-05-04
      • 2014-10-20
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      • 2019-01-20
      • 2011-04-27
      • 2011-05-01
      • 2014-06-19
      相关资源
      最近更新 更多