我已经更新到 EF6,但并不好玩。我创建了一个新的迁移,它只是将两个字段更改为可为空。
public partial class AllowNullableFieldsForImage : DbMigration
{
public override void Up()
{
AlterColumn("dbo.Scabs", "image_height", c => c.Int());
AlterColumn("dbo.Scabs", "image_width", c => c.Int());
}
public override void Down()
{
AlterColumn("dbo.Scabs", "image_width", c => c.Int(nullable: false));
AlterColumn("dbo.Scabs", "image_height", c => c.Int(nullable: false));
}
}
当我运行 update-database
时,出现以下错误:
Cannot insert the value NULL into column 'ContextKey', table 'ScabsContext.dbo.__MigrationHistory'; column does not allow nulls. INSERT fails. The statement has been terminated.
我发现有几篇文章提到了 MigrationHistory 中的新 ContextKey 字段,但没有任何内容可以回答我的问题...为什么此字段为空?有没有办法(我是否需要)为 ContextKey
指定一个值?我以为那是自动完成的?
最佳答案
在我看来,您在进行更改时可能一直在使用数据库来测试迁移。 EF5 迁移历史表具有以下结构:
CREATE TABLE [dbo].[__MigrationHistory](
[MigrationId] [nvarchar](255) NOT NULL,
[Model] [varbinary](max) NOT NULL,
[ProductVersion] [nvarchar](32) NOT NULL
CONSTRAINT [PK_dbo.__MigrationHistory] PRIMARY KEY CLUSTERED
( [MigrationId] ASC )
)
当我将一个项目从 EF5 升级到 EF6 时,我为此添加了一个显式迁移。如果您使用的是十进制字段,那么无论如何都需要进行迁移,因为它无论如何都会使用显式精度重新创建这些字段。当您在 EF6 下运行第一次迁移时,它会使用新结构重新创建迁移历史表,看起来像...
CREATE TABLE [dbo].[__MigrationHistory2] (
[MigrationId] [nvarchar](150) NOT NULL,
[ContextKey] [nvarchar](300) NOT NULL,
[Model] [varbinary](max) NOT NULL,
[ProductVersion] [nvarchar](32) NOT NULL,
CONSTRAINT [PK_dbo.__MigrationHistory2] PRIMARY KEY ([MigrationId], [ContextKey])
)
您可以看到该表包含一个不为空的 ContextKey 字段。由于您遇到的错误,我建议您尝试在 EF6 格式的数据库上使用 EF5 运行迁移。
如果您想将数据库恢复为 EF5 格式以便从 EF5 运行迁移,只需删除 ContextKey 字段并重新创建主键:
ALTER TABLE dbo.__MigrationHistory DROP CONSTRAINT [PK_dbo.__MigrationHistory2]
ALTER TABLE dbo.__MigrationHistory DROP COLUMN ContextKey
ALTER TABLE dbo.__MigrationHistory ADD CONSTRAINT [PK_dbo.__MigrationHistory] PRIMARY KEY (MigrationId)
关于c# - EF 6.0 迁移 : ContextKey in MigrationHistory is null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20685055/