0
我需要創建一個數據庫「任務」,其中所有步驟必須成功完成,否則整個事件將回滾。這可能嗎?如何在一個「工作」中將多個EntityFramework事務捆綁在一起?
例如
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");
}
您要查找的內容稱爲[事務範圍](http://msdn.microsoft.com/fr-fr/library/system.transactions.transactionscope(v = vs.110).aspx)。 – 2014-09-04 15:02:28
@FlorianF .:這是[**英文版**](http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope(v = vs.110).aspx): ) – Nope 2014-09-04 15:06:27
或者只是不停地調用'SaveChanges'。在最終調用'SaveChanges'並且不會產生多個連接之前,您可以使用Entity Framework構建一個完整的對象圖。 – 2014-09-04 15:49:32