Does anybody know how to create an explicit transaction in Entity Framework 7 ??? All the info I find is refered to the version 6 of EF. The documentation is also very incomplete so, could anybody provide an example of it?
I have a dbContext and I must delete an entity and it's related objects, and then insert them again, but in the same transaction, so I'll always have a "version" of the rows.
In all versions of 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.
We add a new Standard entity and Student entity and save them to the database using the SaveChanges() method. This will create a new transaction and execute INSERT commands for Standard and Student entities within a transaction and commit them. After this, we add a new Course entity and call SaveChanges() .
Sometimes though the SaveChanges(false) + AcceptAllChanges() pairing is useful. The most useful place for this is in situations where you want to do a distributed transaction across two different Contexts. If context1. SaveChanges() succeeds but context2.
BeginTransaction() It is a simple and easier method within an existing DbContext to start and complete transactions for users. It allows several operations to be combined within the same transaction and hence either all are committed or all are rolled back as one.
The transaction functionality are included in EF7 starting with RC1 only (see the statement). The call of .SaveChanges()
(or .SaveChangesAsync()
) should use automatic transaction. Then I suppose that the state of some items of the entities should be marked as Deleted before, for example.
One can start transaction explicitly by wrapping some fragment of manipulation on the database inside of
using (context.Database.BeginTransaction()) {
/*do something*/
}
The transaction will be committed by call of .Dispose()
at the end of using
block. One can use alternatively
using (var transaction = await context.Database.BeginTransactionAsync()) {
/*do something*/
/*one can call
transaction.Rollback() or transaction.Commit()
explicitly in the code */
}
It general all should looks like in previous version of Entity Framework. See the post for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With