Code First Migrations数据迁移方法

本文详细介绍了如何使用Entity Framework进行数据库迁移,包括安装、配置、添加迁移、运行迁移等关键步骤,确保数据库更新顺利。

摘自网络,忘记作者了,对不住了。仅作记录以备用:

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值