C# MVC EF框架 用事务

时间:2023-03-09 22:26:00
C#  MVC  EF框架  用事务

using System.Transactions;

[HttpPost]
public JsonResult Update(InfoModel list)
{
using (TransactionScope transaction = new TransactionScope())
{
try
{
string sql = string.Format("update Member set M_Name='{0}', M_Pwd='{1}', M_Sex='{2}' where M_ID={3}", list.M_Name, list.M_Pwd, list.M_Sex, list.M_ID);
string sql2 = string.Format("update Info set S_Hobbies='{0}', S_weight={1}, S_address='{2}' ,S_phone='{3}' where M_ID={4}", list.S_Hobbies, list.S_weight, list.S_address, list.S_phone, list.M_ID);
var result1 = tc.Database.ExecuteSqlCommand(sql) > 0 ? true : false;
var result2 = tc.Database.ExecuteSqlCommand(sql2) > 0 ? true : false;

if (result1 && result2)
{
transaction.Complete();
}
}
catch (Exception ex)
{

return Json(new { result = "1", message = "更新失败! "+ex });
}

}

return Json(new { result = "0", message = "更新成功!" });
}