Database.BeginTransaction()

可以針對單個事務執行多個操作,以便在任何操作失敗時可以回滾更改。

using (var context = new PlanetContext())
{
    using (var transaction = context.Database.BeginTransaction())
    {
        try
        {
            //Lets assume this works
            var jupiter = new Planet { Name = "Jupiter" };
            context.Planets.Add(jupiter);
            context.SaveChanges();

            //And then this will throw an exception
            var neptune = new Planet { Name = "Neptune" };
            context.Planets.Add(neptune);
            context.SaveChanges();

            //Without this line, no changes will get applied to the database
            transaction.Commit();
        }
        catch (Exception ex)
        {
            //There is no need to call transaction.Rollback() here as the transaction object
            //will go out of scope and disposing will roll back automatically
        }
    }
}

請注意,顯式呼叫 transaction.Rollback() 可能是開發人員的慣例,因為它使程式碼更加不言自明。此外,可能有(不太知名的)實體框架的查詢提供程式沒有正確實現 Dipsose,這也需要一個明確的 transaction.Rollback() 呼叫。