- 单个提交,不需要,SaveChanges本来就具有事务属性;
- 如果多个提交保存,使用IDbContextTransaction来解决:
IDbContextTransaction tran = null; try { tran = context.Database.BeginTransaction(); context.UserInfo.Add(new UserInfo() { Name = "haha11", Age = 19 }); context.SaveChanges(); context.UserInfo.Add(new UserInfo() { Name = "haha22", Age = 19 }); context.SaveChanges(); tran.Commit(); } catch (Exception ex) { if (tran != null) tran.Rollback(); Console.WriteLine(ex.Message); } finally { tran.Dispose(); }