Code First Migrations数据迁移方法
摘自网络,忘记作者了,对不住了。仅作记录以备用:
1. To get started just create a simple project, for example a Console Application. After that write the following in the Package Manager Console (In the Visual Studio menu, select View/Other Windows/Package Manager Console). Write the following and hit enter:
PM> Install-Package EntityFramework
2. After the EntityFramework 4.3 is installed we need to enable the database migration. Only one project in our solution can be enabled. To enable migration just enter the following in the Package Manager Console:
PM> Enable-Migrations
3. Now when all the basic configuration of our Migration is setup, we can start adding a migration. We do that by using the command “Add-Migration”. In this example we will add a new column to our Blog table called “Created”. So in the Package Console Manager we write:
PM> Add-Migration AddBlogCreated
4. Now when we have added our AddBlogCreted migration to just simply add a new column, we want to run our migration. We can do it by using the Update-Database command in the Package Manager Console:
PM> Update-Database
5. The Update-Database will now execute all migrations that is added and not “executed” since last update. The timestamp prefix of the migration files as mentioned earlier is used to execute the migration in a correct order. If we run this command we will now have a new column called “Created” in our Blog table.
6. If we also want to see the SQL of the migration we can add the –Verbose parameter after the Update-Database:
PM> Update-Database -Verbose
7. To go to a specific migration, we can use the Update-Database and use the –TargetMigration parameter, for example:
PM> Update-Database –TargetMigration:"AddBlogCreated"
8. This will take us to the “AddBlogCreated” migration state. At the moment we are at this state so nothing will happen. We can try it by going back to a previous state, because we only have one migration we need to back to the first state of the migration (initial state), this is done by set the –TargetMigration value to “$InitialDatabase”:
PM> Update-Database –TargetMigration:$InitialDatabase
-------------------------------------------------
保持专注,只做一件事,做好这件事!@
-------------------------------------------------