无法从 PK 中删除身份属性

Sam*_*Sam 3 entity-framework-5 entity-framework-migrations

我需要将其中一个表上主键的数据类型从 int 更改为字符串(我没有说我想要...)。迁移生成以下代码:

AlterColumn("dbo.Venues", "ID", c => c.String(nullable: false, maxLength: 128));
Run Code Online (Sandbox Code Playgroud)

这会导致 SQL Server 抱怨数据类型必须是 int、bigint 等,因为该列是标识列。我添加了以下内容,但似乎没有效果:

AlterColumn("dbo.Venues", "ID", c => c.Int(identity:false));
Run Code Online (Sandbox Code Playgroud)

问题:如何进行迁移以将数据类型从 int 更改为 string?

以下可能与我的问题有关,但不一定:迁移生成的唯一代码是上面显示的第一个 AlterColumn。当以本机生成方式运行时,迁移导致 SQL Server 抱怨它无法更改列,因为存在依赖关系。事实上,唯一的依赖是它是一个 PK(没有表将它引用为 FK)。我将迁移修改为如下所示,现在我收到了如上所示的数据类型错误。

DropPrimaryKey("dbo.Venues");
AlterColumn("dbo.Venues", "ID", c => c.Int(identity:false));
AlterColumn("dbo.Venues", "ID", c => c.String(nullable: false, maxLength: 128));
AddPrimaryKey("dbo.Venues", "ID");
Run Code Online (Sandbox Code Playgroud)

Eri*_* J. 5

至少对于某些版本的 SQL Server,这可以在不删除/重新创建数据库的情况下完成。据报道,它对 Azure 不起作用(或者在 2015 年的评论中不起作用)。受此答案的启发,是我的 Up() 方法。

请注意,我在这张表上没有任何外键,所以不需要支持链接答案中的皱纹

    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)
    }
Run Code Online (Sandbox Code Playgroud)