C# MVC EF框架 用事务

本文介绍了一个使用 C# 和 System.Transactions 命名空间下的 TransactionScope 类来确保数据库更新操作原子性的方法。通过示例代码展示了如何在一个事务中同时更新两个表的数据,并在遇到异常时回滚事务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 = "更新成功!" });
}

转载于:https://www.cnblogs.com/yyy116008/p/6802796.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值