0
我有一个奇怪的问题。所有文档指出SaveChanges()
方法必须在提交事务之前首先调用,但在我的情况下,如果以这种方式完成,它将抛出异常。 通过调用SaveChanges()
前提交我可以避开“SQL事务完成例外”sql transaction异常
[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();
}
}