Buscar..


Database.BeginTransaction ()

Se pueden ejecutar varias operaciones contra una sola transacción para que los cambios se puedan revertir si falla alguna de las operaciones.

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

Tenga en cuenta que puede ser una convención de desarrolladores para llamar a transaction.Rollback() explícitamente, porque hace que el código sea más fácil de explicar. Además, puede haber proveedores de consultas (menos conocidos) para Entity Framework que no implementen Dipsose correctamente, lo que también requeriría una transaction.Rollback() explícita.Rollback transaction.Rollback() llamada.



Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow