Base solution for your next web application
Open Closed

How to use IUnitOfWorkManager when transaction rollback is required. #6926


User avatar
0
timmackey created

I have a routine that processes files of data to be parsed and written to my db. I'm using IUnitOfWorkManager:

IUnitOfWorkManager unitOfWorkManager;
... initialization ...
try
{
    using (var unitOfWork = unitOfWorkManager.Begin())
    {
        do
        {
            ... process an input file record ...

            if (error_1)
            {
                status.success = false;
                status.FailureReason = "some reason";
                return status;
            }
            else if (error_2)
            {
                status.success = false;
                status.FailureReason = "some other reason";
                throw new Exception("MyException");
            }
            else
            {
                ... get next record from input file ...
            }
        } until EOF;
        unitOfWork.Complete();
        status.success = true;
        return status;
    }
}
catch (Exception ex)
{
    if (ex.Message == "MyException")
    {
        return status;
    }
    status.Success = false;
    status.FailureReason = ex.Message;
    return failure_code_obj;
}

When a failure occurs, I want to abandon the transaction and roll back all records written within the UoW. However, when a failure occurs, instead of rolling back the transaction (by virtue of not calling UoW.Complete() ), the records are written to the db, and the Exception message is "Did not call Complete method of a unit of work." I tried calling UoW.Dispose() , tried throw new Exception("MyException") if error - to no avail. The transaction is not rolled back and my db records are out of sync. I do not want the system default Exception handler to pop up it's message in the browser; I have a custom error modal dialog (the return status; has many fields describing the cause of the error and remedy for the user to fix the problem).

How can I direct UoW to abandon and roll back the current transaction, and return my custom error status?


2 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team

    Try using a new transaction.

    using (var unitOfWork = unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
    

    It may be that the current context is in a unit of work and will not roll back the data unless you throw an exception.

    You can manually control it using a new unit of work.

  • User Avatar
    0
    timmackey created

    That did the trick. A very big THANK YOU!