c# - EF 6.0 迁移 : ContextKey in MigrationHistory is null

标签 c# entity-framework ef-code-first entity-framework-migrations

我已经更新到 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/

相关文章:

c# - 如何将默认 Entity Framework 列添加到现有数据库

c# - EF 代码优先 : Should I initialize navigation properties?

asp.net-mvc - 图像数据库组织

c# - EF4 代码首先添加项目我不是很清楚

c# - 如何在区间条形图中绘制水平线和垂直线 - oxyplot - WPF

c# - 为什么更改时区后 UTC 偏移量相同?

c# - Messenger 默认关闭端口

c# - 从 Selenium webdriver 的当前窗口 GUID 获取窗口句柄 (IntPtr)

entity-framework - EF Code First 没有看到所有迁移

c# - 使用代码优先方法的可空枚举字段不会在数据库中创建枚举字段