Szukaj…


Database.BeginTransaction ()

W ramach jednej transakcji można wykonać wiele operacji, dzięki czemu zmiany mogą zostać wycofane w przypadku niepowodzenia dowolnej operacji.

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
        }
    }
}

Zwróć uwagę, że konwencja deweloperów może wywoływać transaction.Rollback() jawnie, ponieważ sprawia, że kod jest bardziej zrozumiały. Ponadto mogą istnieć (mniej znani) dostawcy zapytań dla Entity Framework, którzy nie wdrażają poprawnie Dipsose , co również wymagałoby jawnej wywołania transaction.Rollback() .



Modified text is an extract of the original Stack Overflow Documentation
Licencjonowany na podstawie CC BY-SA 3.0
Nie związany z Stack Overflow