新手有个事务问题,麻烦大佬指点一下 返回

public static string cs()
{
using (SqlSugarClient db = sqlsguer_db.ljsjk(2))
{
try
{
//开启事务
db.Ado.BeginTran(System.Data.IsolationLevel.ReadCommitted);
//sql1
db.Updateable(实体1).ExecuteCommand();
//sql2
db.Insertable(实体2).ExecuteReturnIdentity();
//sql3
db.Insertable(实体3).ExecuteCommand();
//手动抛异常
throw new Exception("异常");
提交事务
db.Ado.CommitTran();
return "1";
}
catch(Exception ex)
{
try
{
db.Ado.RollbackTran();
}
catch(Exception ex1)
{
写日志;
}
return ex.Message;
}
}
}
为什么,手动抛异常后,数据回滚只回滚了sql3的数据,sql1和sql2的已经写入数据表了
热忱回答(10)
-
fate sta VIP0
1周前1、用插入去测试,插入不会有其他逻辑
2、输出Count观察,这样可以很好的跟踪逻辑是哪里出了错
try { db.BeginTran(); Console.WriteLine(db.Queryable<Order>().Count());//插入前数量 db.Insertable(new Order() { CreateTime=DateTime.Now, Name="aa", Price=1 }).ExecuteCommand(); Console.WriteLine(db.Queryable<Order>().Count());//插入后数量 throw new Exception("出错"); db.CommitTran(); } catch { db.RollbackTran(); Console.WriteLine(db.Queryable<Order>().Count());//回滚后数量 }
0 回复 -
fate sta VIP0
1周前事务这个功能目前是不可能出错的,如果有问题,你可以提供完整DEMO
0 回复 -
fate sta VIP0
1周前如果是MYSQL看一下表的引擎是否支持事务
0 回复 -
hkkjhghgjh VIP0
1周前@fate sta:用的是oracle
db.Ado.BeginTran()
db.Insertable(实体).ExecuteCommand();
db.Ado.CommitTran();
我测试了,如果是只写一个Insertable就回滚正常,两个的话,
db.Ado.RollbackTran();就只回滚最后一条写入的数据,只能写一个Insertable吗,我有点懵了
0 回复 -
fate sta VIP0
1周前@hkkjhghgjh:说了让你规范测试 和写一个2个没有关系,你能保证不是业务引起的错误? 没有时时输出COUNT你怎么知道只回滚一个,不其他触发器等东西影响的
0 回复 -
fate sta VIP0
1周前用插入进行测试,并且时时输出 Count
0 回复 -
hkkjhghgjh VIP0
1周前@fate sta:嗯嗯,好的,我试一下,谢谢
0 回复 -
hkkjhghgjh VIP0
1周前0 回复 -
hkkjhghgjh VIP0
1周前@fate sta :
try
{
db.BeginTran();
db.Insertable(实体
).ExecuteCommand();
//批量插入
db.Insertable(List<实体>
).ExecuteCommand();
throw
new
Exception(
"出错"
);
db.CommitTran();
}
catch
{
db.RollbackTran();
}
这个是不是不能这门用啊,我发现,这样批量插入的可以回滚成功,单条插入的回滚不成功
0 回复 -
fate sta VIP0
1周前@hkkjhghgjh:都支持的,如果还有疑问
https://www.donet5.com/Home/Doc?typeId=2366 按模版写个用例,没完整测试用例不在回复
0 回复