I'm working on an ASP.NET MVC system with Entity Framework, which uses Migrations.
It 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();
}
}
It works correctly in the production environment and some successful migrations have already been performed.
The initial migration is empty which will cause a 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 am going to publish the system to another server that does not contain the database, the initializer will create the database because it does not exist until then. Then in the next access, it will try to run the migrations, giving error, since already the objects of the migrations exist, since they were created by Database.Create
I've tried using Add-Migration InitialCreate, but it creates a blank migration. I was wondering if you have any way to after running the Database.Create command, it would indicate that the last migration has already been executed.
Edit
When running the system when there is no database, it is giving error in the CreateDatabase
- enters the command context.Database.Create ()
- the initial migration passes Error-free Up
- when running the first migration MigrationErroUsuario11122015 gives the below error
- Neither does the GetPendingMigrations ()
Additional information: Foreign key 'FK_dbo.ErrorUserDir.ErrorID' references invalid table 'dbo.Erro'.
I have an impression that I tried to create a table in the "User Error" table but the "Error" table did not yet exist, or the "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);
}