在EF 中怎么使用事务?
这个问题纠结了我好久,直到有人跟我一起讨论,我和同事一起讨论查资料。
查的好多资料都是使用
using (TransactionScope scope = new TransactionScope()) { //具体代码内容
scope.Complete(); }
这种方式。
而我在实际使用中是没法使用的。
所以我就一直找其他的方式,无意中看到某个网站的的database,然后我就采用了下面的方式:
1 using (var dbContext = new TopOnlineDbContext()) 2 { 3 using (var scope = dbContext.Database.BeginTransaction()) 4 { 5 try
6 { 7 if (ids != null) 8 { 9 foreach (var id in ids) 10 { 11 T t = dbContext.Find<T>(id); 12 assfeedback.IsDel = true; 13 dbContext.Update<T>(t); 14 } 15 } 16 scope.Commit();//正常完成就可以提交
17 return 0; 18 } 19 catch (Exception ex) 20 { 21 scope.Rollback();//发生异常就回滚
22 return -1; 23 } 24 } 25 }