Я сталкиваюсь с проблемой при выполнении транзакций в системных таблицах (SQL Azure) в моем приложении Aspnet Core + Entity Framework. Ссылка на объекты) /> Обновить основную сущность. < /li>
Обновить шаги задачи. < /li>
Если задача должна быть выполнена, добавьте сообщение.public async Task HandleGenericOutcomeAsync(int entityId, GenericOutcomeRequest request, CancellationToken cancellationToken)
{
// 1. retrieve main entity
var entity = await _dbContext.Entities.FindAsync([entityId], cancellationToken: cancellationToken);
// 2. Retrieve associated task by entity
var task = await _taskService.GetOpenedTaskByTypeIdAsync(entityId, TaskTypeEnum.TypeA, true, cancellationToken);
// 3. Perform business logic outside transaction
var upcomingPhase = await CalculateNextStepAsync(entityId, request, cancellationToken);
var shouldCompleteTask = upcomingPhase is StepEnum.Done or StepEnum.RequiresVerification;
// 4. Start transaction
var transaction = await _dbContext.Database.BeginTransactionAsync(cancellationToken);
try
{
// 5. Update main entity
switch (request.PreviousPhase)
{
case StepEnum.StepA:
entity.SomeProperty = request.StepAData!.SomeValue;
break;
case StepEnum.StepB:
entity.Notes = request.StepBData!.Note;
break;
}
// 6. Update task's steps.
UpdateTaskSteps(task, (int)request.PreviousPhase, (int)upcomingPhase);
// 7. If task should be completed, append a message.
if (shouldCompleteTask)
{
task.Messages.Add(new Messages
{
Message = message
});
}
// 8. Complete the task.
await _taskService.CompleteAsync(task.Id, cancellationToken);
// 9. Save changes and commit the transaction.
await _dbContext.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
return new GenericOutcomeResponse(upcomingPhase);
}
catch
{
await transaction.RollbackAsync(cancellationToken);
return GenericServiceErrors.GenericError;
}
finally
{
// Dispose the transaction if it was started locally
if (!hasExternalTransaction)
await transaction.DisposeAsync();
}
}
private void UpdateTaskSteps(GenericTask task, int previousPhase, int upcomingPhase)
{
// Get the entity tracking entry for the task
var entry = _dbContext.Entry(task);
// Check if the task is not currently tracked by the context
var isDetached = entry.State == EntityState.Detached;
// Attach the task to the context if it's detached
if (isDetached)
_dbContext.Attach(task);
// Update the task's phase tracking properties
task.SetPreviousPhase(previousPhase);
task.SetUpcomingPhase(upcomingPhase);
// Mark the phase property as modified if the entity was detached
if (isDetached)
entry.Property(x => x.Steps).IsModified = true;
}
< /code>
Проблема возникает, когда я одновременно запускаю этот метод (для разных объектов) и получаю следующую ошибку: < /p>
Произошла ошибка при сохранении изменений объекта. Смотрите исключение Inner
для деталей. Не удалась модификация данных при системе, версированной системой
table 'server.dbo.entities', поскольку время транзакции было раньше, чем время начала периода
для затронутых записей. Есть предложения о том, как это смягчить?
Подробнее здесь: https://stackoverflow.com/questions/796 ... oned-table