Is it necessary to use transaction when registering header and detail, when using EF6?
In your particular case, you do not need it.
First, it must be taken into account that the following sentences still do not send the changes to the database. Rather, they accumulate the changes in memory until you then execute SaveChanges()
. So, so far, there is still no need for a transaction.
//CABECERA
context.Entry(entity).State = EntityState.Added;
//DETALLE
foreach (var d in entity.DetalleCompras)
{
context.Entry(d).State = EntityState.Added;
}
Now, when you run:
context.SaveChanges();
... now yes, EF sends all the cumulative changes to the database, including header and detail. But here you also do not need to worry about handling a transaction manually, because EF automatically handles executing SaveChanges()
within a transaction.
This is made clear by the documentation for EF6 + :
In all versions of the Entity Framework, whenever you execute SaveChanges()
to insert, update or delete on the database the framework will wrap that operation in a transaction. This transaction lasts only long enough to execute the operation and then completes. When you execute another such operation a new transaction is started.
Translated:
In all versions of Entity Framework, when you run SaveChanges()
to add, modify or delete records in the database, EF wraps (or surrounds) the transaction in a transaction. This transaction lasts only long enough for the operation to run, and then it ends. When you execute another operation of this type, a different transaction is started.