EF事务
电脑版发表于:2020/7/30 15:20
EF的SaveChanges默认会开启事务,如果想手动使用事务的话,参考代码如下:
using (var context = new BloggingContext()) { using (var transaction = context.Database.BeginTransaction()) { try { context.Blogs.Add(new Blog { Url = "www.tnblog.net" }); context.SaveChanges(); context.Blogs.Add(new Blog { Url = "m.tnblog.net" }); context.SaveChanges(); var blogs = context.Blogs .OrderBy(b => b.Url) .ToList(); // Commit transaction if all commands succeed, transaction will auto-rollback // when disposed if either commands fails transaction.Commit(); } catch (Exception) { // TODO: Handle failure } } }