gpt4 book ai didi

ef-code-first - EF迁移: Move Table from 2 Column PK to Single Column causes ALTER before DROP and fails

转载 作者:行者123 更新时间:2023-12-04 13:33:42 28 4
gpt4 key购买 nike

我正在使用EF 4.3.1代码优先迁移。我有一张像这样的 table :

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; }
}​

我有一个使用上述代码创建的现有表。然后,我将其移至单列主键:
public class Product
{
[MaxLength(100)]
public string Store { get; set; }

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

这会导致EF在下一次自动迁移中失败,并提示:

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.



显然,在尝试触发此ALTER语句之前,必须先删除PK_Product(为什么要完全更改该列?),但是迁移失败。

我是在做错什么还是这是一个错误?解决方法?

最佳答案

您将无法通过自动迁移来执行此操作。您必须使用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更改了该列,因为当它是 Key的一部分时,它暗含了 NOT NULL
您可以保持原样,添加 [Required]属性,或者在删除PK后允许EF更改列

关于ef-code-first - EF迁移: Move Table from 2 Column PK to Single Column causes ALTER before DROP and fails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11093803/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com