How do I create a migration for an existing databa

2020-06-16 08:48发布

so I want to get started with EntityFramework 4.3 migrations. I wanted to know if I can convert an existing database to a migration-enabled database and have EF assume that only changes from then on should be considered migrations.

3条回答
Melony?
2楼-- · 2020-06-16 09:09

So it seems what I was looking for is Codebased Migrations which is activated when I set AutomaticMigrationsEnabled=false. My models were generated from an existing database. To activate migrations, all I needed to do was enable migrations (Enable-Migrations), create a new new migration file using Add-Migration, empty it out (my models are already in the database so I don't want EF to try and create them) and deploy that. To deploy, I added the following to my Global.asax file:

protected void Application_Start()
{
        var config= new Configuration();
        var migrator = new DbMigrator(config);
        migrator.Update();
}

A new table __MigrationHistory was created and a new migration record was create in it. This new migration record had a hash of my models so now any changes to my models can be scripted for me in future migrations with EF.

To test, I created another migration file (Add-Migration), I added a new property to a model, ran Add-Migrations which scripted the new field and then deployed my application. The migration was run as expected.

查看更多
三岁会撩人
3楼-- · 2020-06-16 09:27

A nice walk-through for this is posted here: http://thedatafarm.com/data-access/using-ef-4-3-code-first-migrations-with-an-existing-database/

The one change I would suggest is to simply comment out the code in the Up and Down methods until you have deployed the migration. After that, you can uncomment the code and that will allow you to create a new database if you need to later.

查看更多
Rolldiameter
4楼-- · 2020-06-16 09:30
登录 后发表回答