Cant remove identity attribute from PK

帅比萌擦擦* 提交于 2019-11-28 14:12:21

Removing an identity specification from a column can only be done by re-creating the table. Look at the ALTER TABLE - ALTER COLUMN statement: there is no syntax to change (add or remove) an identity specification.

So I'm afraid you'll have to do this manually and make a fresh start for subsequent migrations.

BTW Sql Server Management Studio won't help you doing this. You may want to use Toad for Sql Server. It creates a full table rebuild script when you remove an identity specification.

Eric J.

At least for some versions of SQL Server, this can be done without dropping/recreating the database. It reportedly doesn't work for Azure (or didn't as of a 2015 comment). Inspired by this answer, here's my Up() method.

Note that I don't have any foreign keys on this table so don't need to support that wrinkle covered in the linked answer

    public override void Up()
    {
        DropPrimaryKey("dbo.Products"); // Should be same as ALTER TABLE yourTable DROP CONSTRAINT PK_yourTable_id;
        Sql("alter table dbo.Products add tempId int NOT NULL default -1");
        Sql("update dbo.Products set tempId = Id;");
        // Won't work. Can't remove identity: AlterColumn("dbo.Products", "Id", c => c.Int(nullable: false));
        Sql("alter table dbo.Products drop column Id");
        Sql("EXEC sp_rename 'Products.tempId', 'Id', 'COLUMN'");
        AddPrimaryKey("dbo.Products", "Id"); // Should be same as ALTER TABLE yourTable ADD CONSTRAINT PK_yourTable_id PRIMARY KEY (id)
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!