6

I'm using EF 4.3.1 Code First Migrations. I have a table like:

public class Product
{
    [Key]
    [Column(Order=0)]
    [MaxLength(100)]
    public string Store { get; set; }

    [Key]
    [Column(Order=1)]
    [MaxLength(100)]
    public string Sku { get; set; }
}​

I have an existing table created with the above code. I then moved it to a single-column Primary Key:

public class Product
{
    [MaxLength(100)]
    public string Store { get; set; }

    [Key]
    [MaxLength(100)]
    public string Sku { get; set; }
}​

This causes EF to fail in the next automatic migration, complaining:

ALTER TABLE [Product] ALTER COLUMN [Store] nvarchar

The object 'PK_Product' is dependent on column 'Store'. ALTER TABLE ALTER COLUMN Store failed because one or more objects access this column.

Clearly the PK_Product needs to be dropped before attempting to fire this ALTER statement (why is it altering the column at all?), but instead the migration fails.

Am I doing something wrong or is this a bug? Workarounds?

4

1 回答 1

13

您将无法通过自动迁移来执行此操作。您必须使用创建迁移Add-Migration,然后对其进行更改,使其仅修改 PK。

迁移可以很简单:

public partial class TheMigration : DbMigration
{
    public override void Up()
    {
        DropPrimaryKey("Products", new[] { "Store", "Sku" });
        AddPrimaryKey("Products", "Sku");
    }

    public override void Down()
    {
        DropPrimaryKey("Products", new[] { "Sku" });
        AddPrimaryKey("Products", new[] { "Store", "Sku" });
    }
}

EF 正在更改该列,因为当它是 a 的一部分时Key,它是隐含的NOT NULL。您可以保持原样、添加属性或允许 EF 在删除 PK[Required]更改列。

于 2012-06-19T19:58:12.123 回答