Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How use Transaction in EntityFramework 5?

I want to trancate some table same time. If one not success, must be all rolback.

Something like that:

ctx.Database.ExecuteSqlCommand("truncate table tb_expensesall");
ctx.Database.ExecuteSqlCommand("truncate table tb_wholesale");
ctx.Database.ExecuteSqlCommand("truncate table tb_singlesale");
ctx.Database.ExecuteSqlCommand("truncate table tb_purchase");

But the problem is , I dont know how use transaction for this.

I trying this:

using (gasstationEntities ctx = new gasstationEntities(Resources.CONS))
{
    ctx.Database.Connection.Open();
    DbTransaction tr = ctx.Database.Connection.BeginTransaction();

    try
    {
        ctx.Database.ExecuteSqlCommand("truncate table tb_expensesall");
        ctx.Database.ExecuteSqlCommand("truncate table tb_wholesale");
        ctx.Database.ExecuteSqlCommand("truncate table tb_singlesale");
        ctx.Database.ExecuteSqlCommand("truncate table tb_purchase");
        //commit the transaction
        tr.Commit();
        new MessageWindow(this, Resources.GetString("Warn"), Resources.GetString("DeleteSuccess"));
    }
    catch (Exception ex)
    {
        //return
        tr.Rollback();
    }
    //close
    ctx.Database.Connection.Close();
}

The problem here: tr.Commit(); and the Exception tell me :

{System.InvalidOperationException: Connection must be valid and open to rollback transaction

And the tr.Rollback(); throw exception to. the exception is:

{System.InvalidOperationException: Connection must be valid and open to rollback transaction

The realy funy thing is , the table truncate is success. what? the commmit is throw exception . and it can be success? i can't understand.

Please tel me what is goning on . if you give me a solution, that's even better.

like image 506
qakmak Avatar asked Dec 13 '12 16:12

qakmak


People also ask

How do I use transactions in EF core?

This feature was introduced in EF Core 5.0. When SaveChanges is invoked and a transaction is already in progress on the context, EF automatically creates a savepoint before saving any data. Savepoints are points within a database transaction which may later be rolled back to, if an error occurs or for any other reason.

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

Can you have transaction support in Entity Framework?

Entity Framework internally maintains transactions when the SaveChanges() method is called. It means the Entity Framework maintains a transaction for the multiple entity insert, update and delete in a single SaveChanges() method.

How is EF transaction Management done?

What EF does by default. 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.


2 Answers

Try this, Technically, the using should commit the transaction when there are no exceptions, but in case of exception, the using will automatically rollback it.

using (var txn = new TransactionScope())
{
    ctx.Database.ExecuteSqlCommand("truncate table tb_expensesall");
    ctx.Database.ExecuteSqlCommand("truncate table tb_wholesale");
    ctx.Database.ExecuteSqlCommand("truncate table tb_singlesale");
    ctx.Database.ExecuteSqlCommand("truncate table tb_purchase");
    txn.Complete();
}
new MessageWindow(this, Resources.GetString("Warn"), Resources.GetString("DeleteSuccess"));
like image 181
humblelistener Avatar answered Oct 10 '22 06:10

humblelistener


Add reference to System.Transactions, import using System.Transactions; and then try to encapsulate your code by

using (gasstationEntities ctx = new gasstationEntities(Resources.CONS))
{
   using (var scope = new TransactionScope())
   {
      [... your code...]

      scope.Complete();
   }
}

If exception occurs, scope.Complete() is not called and the rollback is automatic.

EDIT : I've just seen your MySql tag. If this doesn't work, have a look here !

like image 30
JYL Avatar answered Oct 10 '22 06:10

JYL