我如何将几个EntityFramework事务捆绑在一个“;工作”;
本文关键字:一个 工作 EntityFramework 几个 事务 | 更新日期: 2023-09-27 18:20:36
我需要创建一个数据库"任务",其中所有步骤都必须成功完成,否则整个任务就会回滚。这可能吗?
例如
public ActionResult Create()
{
// Get list of current season pass holders
var seasonPasses = db.SeasonPasses;
// Create a new game
var game = new Game { Description = "Next Game", RegistrationOpen = Convert.ToDateTime("09/08/2014"), RegistrationClose = Convert.ToDateTime("09/12/2014") };
db.Games.Add(game);
if (db.SaveChanges() > 0)
{
foreach (var pass in seasonPasses)
{
// Create new reservations for all the season pass holders
var res = new Reservation { Game = game, SpaceNumber = pass.SpaceNumber, User = pass.User };
db.Reservations.Add(res);
}
// If every season pass holder received a new reservation
if (db.SaveChanges() == seasonPasses.Count())
{
// Show success message
return View("SuccessMessage");
}
}
// If ANYTHING fails...
/******************************************
* Roll Everything Back To The Way it Was *
* '/ Then Show Failure Message '/ *
* ****************************************/
return View("FailureMessage");
}
您可以使用以下交易:
var transaction = _context.Database.BeginTransaction();
//Doing some operations with your context.
transaction.Commit();
transaction.Rollback();
在事务处理过程中,您可以使用SaveChanges()方法,但在为事务调用Commit()方法之前,更改不会应用于数据库。