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