Changing the type of a property with EF Code First

本文详细介绍了如何在数据库迁移中更改数据类型并更新数据的方法,包括添加新列、使用SQL语句迁移数据、删除旧列及重命名新列等步骤。通过遵循此流程,可以确保数据迁移过程的高效性和准确性。

The smartest way is probably to not alter types. If you need to do this, I'd suggest you to do the following steps:

  1. Add a new column with your new type

  2. Use Sql() to take over the data from the original column using an update statement

  3. Remove the old column

  4. Rename the new column

This can all be done in the same migration, the correct SQL script will be created. You can skip step 2 if you want your data to be discarded. If you want to take it over, add the appropriate statement (can also contain a switch statement).

Unfortunately Code First Migrations do not provide easier ways to accomplish this.

Here is the example code:

  AddColumn("dbo.People", "LocationTmp", c => c.Int(nullable: false)); 
Sql(@"
    UPDATE dbp.People
    SET LocationTmp =
        CASE Location
            WHEN 'London' THEN 1
            WHEN 'Edinburgh' THEN 2
            WHEN 'Cardiff' THEN 3
            ELSE 0
        END
    ");
DropColumn("dbo.People", "Location");
RenameColumn("dbo.People", "LocationTmp", "Location");

 

转载于:https://www.cnblogs.com/dupeng0811/p/4878157.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值