Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Altering a nullable column to be not nullable with a default value fails during migration #26807

Closed
ChristopherHaws opened this issue Nov 23, 2021 · 3 comments

Comments

@ChristopherHaws
Copy link
Contributor

The following migration results in the following SQL migration script which fails. The ADD DEFAULT query should run before the ALTER COLUMN script.

migrationBuilder.AlterColumn<string>(
    name: "Column",
    schema: "Schema",
    table: "Table",
    type: "nvarchar(max)",
    nullable: false,
    defaultValueSql: "'[]'",
    oldClrType: typeof(string),
    oldType: "nvarchar(max)",
    oldNullable: true);
ALTER TABLE [Schema].[Table] ALTER COLUMN [Column] nvarchar(max) NOT NULL;
ALTER TABLE [Schema].[Table] ADD DEFAULT ('[]') FOR [Column];

SQL Exception

Cannot insert the value NULL into column 'Column', table 'db.Schema.Table'; column does not allow nulls. UPDATE fails. 

Include provider and version information

EF Core version: 6.0.0
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 6
Operating system: Windows 11
IDE: Visual Studio 2022

@ChristopherHaws ChristopherHaws changed the title Altering nullable column to be not nullable with a default value fails during migration Altering a nullable column to be not nullable with a default value fails during migration Nov 23, 2021
@ajcvickers
Copy link
Member

Duplicate of #21765? /cc @bricelam

@HerrNiklasRaab
Copy link

Same here, but in my case, the column I want to make non-nullable has no null values, but it still fails to migrate. Which seems different then this issue, what is described here: #21765 (comment)

@roji
Copy link
Member

roji commented Nov 30, 2021

The ADD DEFAULT query should run before the ALTER COLUMN script.

The ordering actually doesn't matter - if we add the default before making the column non-nullable, you still get the error (see https://github.com/npgsql/npgsql/issues/4186#issuecomment-982512914). And yeah, seems like this is a dup of #21765.

@ajcvickers ajcvickers reopened this Oct 16, 2022
@ajcvickers ajcvickers closed this as not planned Won't fix, can't repro, duplicate, stale Oct 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants