Skip to content

Need to modify some of the migration service example codes #2357

Closed
@calmbino

Description

@calmbino

An official documentation page that needs to be modified

You must modify some of the RunMigrationAsync method content in the Worker.cs example code in the SupportTicketApi.MigrationService project.

    private static async Task RunMigrationAsync(TicketContext dbContext, CancellationToken cancellationToken)
    {
        var strategy = dbContext.Database.CreateExecutionStrategy();
        await strategy.ExecuteAsync(async () =>
        {
            // Run migration in a transaction to avoid partial migration if it fails.
            await using var transaction = await dbContext.Database.BeginTransactionAsync(cancellationToken);
            await dbContext.Database.MigrateAsync(cancellationToken);
            await transaction.CommitAsync(cancellationToken);
        });
    }

Because ExecuteAsync manages transactions, an exception occurs when there is a custom (external) transaction.

Note

I have customised the User table by inheriting from IdentityUser.

System.NotSupportedException: User transaction is not supported with a TransactionSuppressed migrations or a retrying execution strategy.

A transaction was started before applying migrations. This prevents a database lock to be acquired and hence the database will not be protected from concurrent migration applications. The transactions and execution strategy are already managed by EF as needed. Remove the external transaction.

Therefore, it should be amended as follows

    private static async Task RunMigrationAsync(TicketContext dbContext, CancellationToken cancellationToken)
    {
        var strategy = dbContext.Database.CreateExecutionStrategy();
        await strategy.ExecuteAsync(async () =>
        {
            await dbContext.Database.MigrateAsync(cancellationToken);
        });
    }

or

    private static async Task RunMigrationAsync(TicketContext dbContext, CancellationToken cancellationToken)
    {
        var strategy = dbContext.Database.CreateExecutionStrategy();
        await strategy.ExecuteAsync(dbContext.Database.MigrateAsync, cancellationToken);
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions