Cannot insert the value NULL into column ‘ContextKey’ ?

Cannot insert the value NULL into column ‘ContextKey’, table ‘TestDb.dbo.__MigrationHistory’; column does not allow nulls. INSERT fails. The statement has been terminated.
Exception Type : System.Data.SqlClient.SqlException

We will get this error while upgrading EF 5.0 to EF 6.0

An EF5 Migration History table has the following structure:

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 )
)

When we upgrade EF 5.0 to EF 6.0 then it recreates the migration history table using the new structure, which looks like…

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])
)

This table includes a new column ContextKey which is not null. So we are getting this error.

If you want to revert your database to the EF5 format in order to run a migration from EF5, just drop the ContextKey field and recreate the primary key:

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)

Programming is Easy…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s