efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Database.Migrate fails after first run

Open Reza-Noei opened this issue 2 years ago • 12 comments

Database.Migrate fails after first run

I have a WebApi application which works with MSSQL. Everything is fine in development (with VS 2022), migration works fine, database is persisted, ... I have tried to publish some docker images; And when It came to testing, I've got some unexpected behavior from EFCore, When I run the application at the first time, It creates the database and applies the migration, everything looks fine. but when I run the application for the second time It seems that EF is not able to recognize the database and what it done at the previous run.

C# Migration codes

    private async Task InitializeDatabase(IApplicationBuilder app)
    {
        using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
        {
            BusinessDomainContext businessDomainContext = serviceScope.ServiceProvider.GetRequiredService<BusinessDomainContext>();
            await businessDomainContext.Database.MigrateAsync();
        }
    }

Docker Compose content

 version: '3'
 services:
     db:
         image: mcr.microsoft.com/mssql/server
         container_name: db
         ports:
             - 1533:1433
         environment:
             - ACCEPT_EULA=Y
             - MSSQL_SA_PASSWORD=******
         user: root
         volumes:
             - ./mssql:/var/opt/mssql/data
    kava-service:
        image: service:1.0.0
        container_name: kava-service
        expose:
            - 9001
        ports:
            - 9001:9001
        depends_on:
            - db
        environment:
            - ASPNETCORE__ENVIRONMENT=Production
            - AUTO__MIGRATE=true
            - ConnectionStrings__BusinessDomainConnectionString=Server=db;Initial Catalog=Kava.BusinessDomain;User ID=sa;pwd=****;MultipleActiveResultSets=true;

StackTrace

Here is what I've got from docker-compose up:

2023-12-25 15:41:49.52 Logon       Error: 18456, Severity: 14, State: 38.
2023-12-25 15:41:49.52 Logon       Login failed for user 'sa'. Reason: Failed to open the explicitly specified database 'Kava.BusinessDomain'. [CLIENT: 172.18.0.3]
2023-12-25 15:41:49.52 spid44s     Database 'model_msdb' running the upgrade step from version 945 to version 946.
2023-12-25 15:41:49.53 spid44s     Database 'model_msdb' running the upgrade step from version 946 to version 947.
2023-12-25 15:41:49.54 spid44s     Database 'model_msdb' running the upgrade step from version 947 to version 948.
2023-12-25 15:41:49.55 spid44s     Database 'model_msdb' running the upgrade step from version 948 to version 949.
2023-12-25 15:41:49.56 spid44s     Database 'model_msdb' running the upgrade step from version 949 to version 950.
2023-12-25 15:41:49.57 spid44s     Database 'model_msdb' running the upgrade step from version 950 to version 951.
2023-12-25 15:41:49.63 spid44s     Database 'model_msdb' running the upgrade step from version 951 to version 952.
2023-12-25 15:41:49.64 spid44s     Database 'model_msdb' running the upgrade step from version 952 to version 953.
2023-12-25 15:41:49.66 spid44s     Database 'model_msdb' running the upgrade step from version 953 to version 954.
2023-12-25 15:41:49.68 spid44s     Database 'model_msdb' running the upgrade step from version 954 to version 955.
2023-12-25 15:41:49.69 spid44s     Database 'model_msdb' running the upgrade step from version 955 to version 956.
kava-service          | Unhandled exception. Microsoft.Data.SqlClient.SqlException (0x80131904): Database 'Kava.BusinessDomain' already exists. Choose a different database name.
kava-service          |    at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
kava-service          |    at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
kava-service          |    at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
kava-service          |    at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
kava-service          |    at Microsoft.Data.SqlClient.SqlCommand.InternalEndExecuteNonQuery(IAsyncResult asyncResult, Boolean isInternal, String endMethod)
kava-service          |    at Microsoft.Data.SqlClient.SqlCommand.EndExecuteNonQueryInternal(IAsyncResult asyncResult)
kava-service          |    at Microsoft.Data.SqlClient.SqlCommand.EndExecuteNonQueryAsync(IAsyncResult asyncResult)
kava-service          |    at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
kava-service          | --- End of stack trace from previous location ---
kava-service          |    at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQueryAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
kava-service          |    at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQueryAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
kava-service          |    at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQueryAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
kava-service          |    at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQueryAsync(IEnumerable`1 migrationCommands, IRelationalConnection connection, CancellationToken cancellationToken)
kava-service          |    at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQueryAsync(IEnumerable`1 migrationCommands, IRelationalConnection connection, CancellationToken cancellationToken)
kava-service          |    at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQueryAsync(IEnumerable`1 migrationCommands, IRelationalConnection connection, CancellationToken cancellationToken)
kava-service          |    at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQueryAsync(IEnumerable`1 migrationCommands, IRelationalConnection connection, CancellationToken cancellationToken)
kava-service          |    at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.CreateAsync(CancellationToken cancellationToken)
kava-service          |    at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.MigrateAsync(String targetMigration, CancellationToken cancellationToken)
kava-service          |    at BSN.Kava.Service.Startup.InitializeDatabase(IApplicationBuilder app) in /src/Source/BSN.Kava.Service/Startup.cs:line 147
kava-service          |    at BSN.Kava.Service.Startup.Configure[App](App app, IWebHostEnvironment env) in /src/Source/BSN.Kava.Service/Startup.cs:line 101
kava-service          |    at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__128_1(Object state)
kava-service          |    at System.Threading.QueueUserWorkItemCallbackDefaultContext.Execute()
kava-service          |    at System.Threading.ThreadPoolWorkQueue.Dispatch()
kava-service          |    at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart()
kava-service          |    at System.Threading.Thread.StartCallback()
kava-service          | ClientConnectionId:11f163e5-86ab-4c8d-b8eb-7ec4101f60d5
kava-service          | Error Number:1801,State:3,Class:16
2023-12-25 15:41:49.77 spid44s     Database 'model_msdb' running the upgrade step from version 956 to version 957.

Provider and Version information

EF Core version: 6.0.19 Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: .NET 6.0 Operating system: Windows 11 Version: 22H2, OS Build: 22621.2861 IDE: Visual Studio 2022 17.7.7

Installed Packages

Microsoft.EntityFrameworkCore.Tools Version 6.0.16 Microsoft.EntityFrameworkCore Version 6.0.19 Microsoft.EntityFrameworkCore.Proxies Version 6.0.19 Microsoft.EntityFrameworkCore.Relational Version 6.0.19 Microsoft.EntityFrameworkCore.SqlServer Version 6.0.19

Reza-Noei avatar Dec 25 '23 13:12 Reza-Noei

I have the same problem here.

meghasemim1999 avatar Dec 25 '23 13:12 meghasemim1999

This issue is lacking enough information for us to be able to fully understand what is happening. Please attach a small, runnable project or post a small, runnable code listing that reproduces what you are seeing so that we can investigate.

ajcvickers avatar Jan 03 '24 14:01 ajcvickers

@ajcvickers

I have written a complete sample for this issue. Everything looks minimal I think.

https://github.com/Reza-Noei/AspNetCoreEFIssue

Reza-Noei avatar Jan 04 '24 13:01 Reza-Noei

@Reza-Noei I am still not able to reproduce this. What happens if you do something simple with the database that doesn't involve EF Core? Does it find the database then?

ajcvickers avatar Jan 17 '24 17:01 ajcvickers

@ajcvickers I have worked on this issue in my development environment. The main issue was with the SqlConnection as you can see in my docker-compose.yml, I was trying to run my WebApplication right after running the mssql container. At this point, my application was unable to connect to this mssql container, so it was unable to retrieve the list of 'AppliedMigrations'. As a result, it tries to apply all the migrations at once, but mssql responds with Target database already exists.... The application is unable to proceed and shuts down.

I have tried to solve this issue, there are couple of solutions for this at this Stackoverflow question.

I had some problems with provided solutions also. By now I'm using restart: always in my docker-compose.yml which will restart my application after each failure. It works after a couple of failure.

I will try to make use of more logical solutions if it was possible.

Reza-Noei avatar Jan 18 '24 12:01 Reza-Noei

@Reza-Noei Thanks for the analysis. I'll check if anyone on the team has ideas around this.

ajcvickers avatar Jan 18 '24 18:01 ajcvickers

@SamMonoRT Can you find the appropriate place to get guidance on container deployments?

ajcvickers avatar Jan 25 '24 18:01 ajcvickers

@richlander - do we have any documentation around container deployments we can take a look to understand this better, or any thoughts on how to proceed here?

SamMonoRT avatar Jan 25 '24 18:01 SamMonoRT

@ajcvickers Why this issue closed? when @SamMonoRT question leave without any answer

soroshsabz avatar Feb 15 '24 09:02 soroshsabz

@ajcvickers I think there are some serious issues with 'EFCore's Migration in production and it can't left ignored.

Reza-Noei avatar Feb 15 '24 15:02 Reza-Noei

The current recommendation would be to use Aspire with https://github.com/davidfowl/WaitForDependenciesAspire/ that uses a health check to wait until the container is ready before trying to apply the migrations. We are working on improving the experience for 9.0

AndriySvyryd avatar Jun 20 '24 23:06 AndriySvyryd

@AndriySvyryd We need something to solve it Production environment. as I read from the Aspire documentations, DotNet Aspire is a development facility that deals with development and we should have some equivalents in Docker-compose or Kubernetes or Azure azd.

Reza-Noei avatar Jun 25 '24 14:06 Reza-Noei