michasaucer
michasaucer

Reputation: 5228

EFMigrationsHistory table is empty

Im creating database in debug. When database not exist, i create new one:

public static void Main(string[] args)                           
{                                                                
    var host = CreateHostBuilder(args).Build();                  
                                                                 
    using (var scope = host.Services.CreateScope())              
    {                                                            
        var services = scope.ServiceProvider;                    
                                                                 
        try                                                      
        {                                                        
            var context = services.GetService<LolDbContext>();   
                                                               
            context?.Database.EnsureCreated();                                                                  
            if (context.Database.CanConnect())
            {                                                    
                context.Database.Migrate();                      
            }                                                    
                                                                 
        }                                                        
        catch (Exception ex)                                     
        {                                                        
            var logger = services.GetRequiredService<ILogger>(); 
            logger.Error($"Exception while migrating db: {ex}"); 
        }                                                        
    }                                                            
                                                                 
    host.Run();                                                  
}                                                                

After app starts i get this exception:

[11:47:10 [Error] Exception while migrating db: Microsoft.Data.SqlClient.SqlException (0x80131904): There is already an object named 'Table' in the database.
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean isAsync, Int32 timeout, Boolean asyncWrite)
   at Microsoft.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String methodName)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade databaseFacade)
   at eSportsLab.LeagueOfLegends.Api.Frontend.Program.Main(String[] args) in D:\repos\lol-sumeron-app\LeagueOfLegends\Presentation\eSportsLab.LeagueOfLegends.Api.Frontend\Program.cs:line 32
ClientConnectionId:00b6a255-f82d-49b2-adf6-23b83d0aeb1b
Error Number:2714,State:6,Class:16

When i go to SSMS i can see created database (with tables, data as expected), but table [__EFMigrationsHistory] is empty. In another database everything works fine:

enter image description here

My question is, why EF dont tracking migrations when i initialize DB like that?

Upvotes: 1

Views: 708

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205539

Shortly, you should not use EnsureCreated if you are using migrations.

Apply migrations at runtime section of the official EF Core documentation contains the following Warning:

  • Don't call EnsureCreated() before Migrate(). EnsureCreated() bypasses Migrations to create the schema, which causes Migrate() to fail.

Upvotes: 3

Related Questions