简体   繁体   English

SQL事务完成异常

[英]Sql transaction is complete exception

I have a strange problem. 我有一个奇怪的问题。 All documentation states that the SaveChanges() method must be first called before committing the transaction but in my case it is throwing an exception if done this way. 所有文档都指出,在提交事务之前必须首先调用SaveChanges()方法,但就我而言,这样做会引发异常。 By calling Commit before SaveChanges() I can avoid the "Sql transaction is complete exception" 通过在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();
            }
        }

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

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

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