ASP.NET CORE Using Transactions

2018-01-31 10:58:28来源:oschina作者:donald121人点击

分享
Default transaction behavior

By default, if the database provider supports transactions, all changes in a single call toSaveChanges()are applied in a transaction. If any of the changes fail, then the transaction is rolled back and none of the changes are applied to the database. This means thatSaveChanges()is guaranteed to either completely succeed, or leave the database unmodified if an error occurs.


Controlling transactions

You can use theDbContext.DatabaseAPI to begin, commit, and rollback transactions. The following example shows twoSaveChanges()operations and a LINQ query being executed in a single transaction.


Not all database providers support transactions. Some providers may throw or no-op when transaction APIs are called.


using (var context = new BloggingContext())
{
using (var transaction = context.Database.BeginTransaction())
{
try
{
context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" });
context.SaveChanges();
context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/visualstudio" });
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
}
}
}

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台