简体   繁体   中英

Error securing a transaction Entity Framework "_dataContext.Database.BeginTransaction()"

I am trying to secure a transaction through Entity Framework. When I use BeginTransaction , ASP.NET throws an exception:

The configured execution strategy 'SqlServerRetryingExecutionStrategy' does not support user initiated transactions. Use the execution strategy returned by 'DbContext.Database.CreateExecutionStrategy()' to execute all the operations in the transaction as a retriable unit.

This is my code inside the repository

public async Task<EvaluationFormQuestionAnswer> AddScore(EvaluationFormQuestionAnswer evaluationFormQuestionAnswer)
{
    evaluationFormQuestionAnswer.Id = Guid.NewGuid();
    evaluationFormQuestionAnswer.EvaluatorId = _identityService.Identity.CurrentAccount.Id;

    using (var transaction = _dataContext.Database.BeginTransaction())
    {
        try
        {
            var result = await _dataContext.EvaluationFormQuestionAnswer.AddAsync(evaluationFormQuestionAnswer);
            await _dataContext.SaveChangesAsync();
            transaction.Commit();
            return result.Entity;
        }
        catch (Exception ex)
        {
            transaction.Rollback();
            throw new ArgumentException("Error", ex);
        }
    }
}

This should work:

var strategy = _dataContext.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () =>
        {
            ...<Your Using Block>...
        });

Wrap it in the execution strategy as shown above and your code should work fine.

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