Search code examples
sql-serveref-core-8.0

EF Core runtime migrations fail on creating database


Problem

On first startup of my application, i try to create the database or execute all pending migrations. When the database doesn't exist yet, it creates the database and then throws an error before applying any migrations.

Recreating

The versions of applications/packages:

SQL-server    Microsoft SQL Server 2022 - 16.0.4105.2 Express Edition (64-bit) on Linux (Ubuntu 
22.04.3 LTS) 

Microsoft.EntityFrameworkCore 8.0.2
Microsoft.EntityFrameworkCore.Design 8.0.2
Microsoft.EntityFrameworkCore.SqlServer 8.0.2

dotnet-ef global tool 8.0.2

The code when my app starts:

using var context = scope.ServiceProvider.GetRequiredService<MyContext>();
context.Database.Migrate();

Tried several times and sometimes I got a timeout exception but sometimes, the migrations went on for minutes (+10).

My SQL-user in the connectionstring has sysadmin rights.

The weird thing is that migrating using the dotnet-ef update commmand works perfectly:

PM> dotnet ef database update

Expected behavior

I would assume that 'context.Database.Migrate();' does the same thing as 'dotnet ef database update': creating and migrating the targetted database.


Solution

  • Turns out there was another process trying to access the database. I had NLog configured to log write its logs into a table of the same database. In the NLog.config, the throwsExceptions was set to false. By disabling the logs while database isn't created yet, the problem was solved.