我有一个奇怪的问题。所有文档都声明必须在提交事务之前首先调用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();
}
}
答案 0 :(得分:0)
nvm解决了这个错误我在调用Commit之前添加了db.SaveChanges()方法