Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit transaction in Entity Framework 7

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.

like image 978
Vi100 Avatar asked Dec 21 '15 16:12

Vi100


People also ask

Does Entity Framework support transactions?

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.

How do I add transactions in Entity Framework?

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() .

When would you use SaveChanges false AcceptAllChanges ()?

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.

Which method on DbContext is called to commit all the changes to database?

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.


1 Answers

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.

like image 112
Oleg Avatar answered Sep 29 '22 08:09

Oleg