简体   繁体   中英

Is it necessary to use transaction scope for these lines

I have two tables in Oracle one of them is MtcUnverified seconds is MtcExit

private bool Verify(Mtcexittran mtcExitTran)
{
    try
    {

        var mtcUnverified = _centraldbContext.Mtcunverifiedtran.FirstOrDefault(a => a.Transactionid.Equals(mtcExitTran.Transactionid));

        if (mtcUnverified == null)
        {
            return false;
        }

        _centraldbContext.Mtcunverifiedtran.Remove(mtcUnverified);

        _centraldbContext.Mtcexittran.Add(mtcExitTran);

        _centraldbContext.SaveChanges();

        return true;
    }

    catch (Exception ex)
    {
       
        return false;
    }

}

My goal is to delete the record from mtcunverified table and insert it to mtcexit table. Do I need to use transactionscope in this code? Is there a possibility that the record will be deleted from the mtcunverified table and not inserted in mtcexit? If the record cannot be added to mtcexit, I want to rollback the deletion from the mtcunverified table. The savechanges method is already creating begin transactions. Therefore, if even one of the two processes is problematic, I think that savechanges will rollback the 2 process. Or do I have to use transactionscope? Thanks for your help.

In the documentation, under "Save Data/Transaction" , it says

By default, if the database provider supports transactions, all changes in a single call to SaveChanges are applied in a transaction. If any of the changes fail, then the transaction is rolled back and none of the changes are applied to the database. This means that SaveChanges is guaranteed to either completely succeed, or leave the database unmodified if an error occurs.

For most applications, this default behavior is sufficient. You should only manually control transactions if your application requirements deem it necessary.

So, unless you've done something to stop EF using transactions, the default should be fine.

If you want more advanced transaction control, with a transaction spanning multiple calls to SaveChanges , and with "savepoints" that you can roll back to, that's described in the same part of the documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM