initial code migration not working
I am trying to run migrations from code. I created my models and enabled-migrations and then added initial migration, this initial migration contains all the create tables etc
public partial class Initial : DbMigration
{
public override void Up()
{
CreateTable(..........
}
public override void Down()
{
DropTable(...........
}
}
I then tried the Update-Database command from the visual studio which works fine, creates the database and runs the initial migration.
I then delete the database from the Sql Studio. Then I run the console app that calls the Migration Manager class
// MigrationManager class
public static bool PerformMigration(string migrationId)
{
bool success = false;
try
{
DbMigrationsConfiguration<MyDbContext> config = new Configuration();
....
DbMigrator migrator = new DbMigrator(config);
migrator.Configuration.AutomaticMigrationsEnabled = false;
if (string.IsNullOrEmpty(migrationId))
migrator.Update(); --> fails saying pending migration
else
migrator.Update(migrationId);
success = true;
}
catch (Exception e)
{
success = false;
LastException = e.Message;
}
return success;
}
The Update() fails with the following error:
Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.
//Configuration.cs
internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(WorkflowConfigurationDbContext context)
{
SeedData(context);
}
private void SeedData(){...}
}
public class MyDbContext : DbContext
{
public MyDbContext()
{
}
public DbSet....
}
When I step through the Update() call, it goes into Configuration() constructor and MyDbContext() constructor but fails after that, it seems like its not trying the Initial migration at all.
Make sure the database initialization strategy is correct in your EF context's constructor, like:
public partial class YourContext: DbContext
{
static YourContext()
{
Database.SetInitializer<YourContext>(new CreateDatabaseIfNotExists<YourContext>());
}
}
This is executed the first time the database is accessed.
EDIT: A second issue may be about security: does the user that is executing the migration have the required permissions?
发现这个问题,它是不正确的命名空间。
DbMigrationsConfiguration<MyDbContext> config = new Configuration();
config.MigrationsNamespace = "Correct Namespace";
链接地址: http://www.djcxy.com/p/90256.html
上一篇: 使用EF迁移将现有数据库列添加到模型中
下一篇: 初始代码迁移不起作用