您的位置:首页 > 编程语言 > ASP

ASP.NET CORE Using Transactions

2018-01-30 00:00 706 查看

Default transaction behavior

By default, if the database provider supports transactions, all changes in a single call to
SaveChanges()
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 that
SaveChanges()
is guaranteed to either completely succeed, or leave the database unmodified if an error occurs.

Controlling transactions

You can use the
DbContext.Database
API to begin, commit, and rollback transactions. The following example shows two
SaveChanges()
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
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  .NET Core ASP.NET MVC