3
I am working on an ASP.NET MVC system with Entity Framework, which uses Migrations.
Has the following initializer:
public void InitializeDatabase(Contexto context)
{
if (!context.Database.Exists())
{
context.Database.Create();
}
else
{
// se tiver migrações pendentes,irá executar essas
var migrator = new DbMigrator(_configuration);
if (migrator.GetPendingMigrations().Any())
migrator.Update();
}
}
Is working correctly in the production environment having already been executed some migrations successfully.
The initial migration is empty which will cause problem in another scenario that I will talk about below.
public partial class InitialCreate : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
If I go to publish the system on another server that does not contain the database, the initializer will create the database because it does not exist, until then ok. Then in the next access, it will try to run the migrations, giving error, as there are already the migrations objects, as they were created by Database.Create
I tried using Add-Migration Initialcreate, but it creates a blank migration. I wanted to know if there is any way after executing the Database.Create command, it would indicate that the last migration has already been executed.
Edit
When running the system when there is no bank, you are giving error in the Createdatabase command
- enters context.Database.Create command()
- the initial migration goes through the Up without errors
- running the first migration Migrationerrousuario11122015 gives the error below
- nor arrives at the Getpendingmigrations check()
Additional information: Foreign key 'Fk_dbo.Error_dbo.Erro_erroid' invalid table 'dbo. Error'.
I have the impression that tried to create in the table "Errousuario" but the table "Error" did not exist yet, or was not commited to the table create "Error"
public partial class MigrationErroUsuario11122015 : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.ErroUsuario",
c => new
{
ErroUsuarioID = c.Int(nullable: false, identity: true),
ErroID = c.Int(nullable: false),
UsuarioID = c.Int(nullable: false),
})
.PrimaryKey(t => t.ErroUsuarioID)
.ForeignKey("dbo.Erro", t => t.ErroID, cascadeDelete: true)
.ForeignKey("dbo.Usuario", t => t.UsuarioID, cascadeDelete: true)
.Index(t => t.ErroID)
.Index(t => t.UsuarioID);
}
I’ll add some details in the question. the error is giving in Createdatabase, nor arrived in the migrations part of the changed algorithm.
– user26552
@Murilo I edited the answer.
– Leonel Sanches da Silva