'EF Core 6 adds a default value in SQL when nullable reference types are on and a column is changed from string? to string

Nullable Reference Types are turned on for my project and I have an entity in my EF Core model which had a string? property that I changed to string.

old:

public string? Name { get; set; };

new:

public string Name { get; set; } = default!;

I then generated a migration and EF added a default value to the column

migrationBuilder.AlterColumn<string>(
    name: "Name",
    table: "MyTable",
    type: "varchar(25)",
    unicode: false,
    maxLength: 25,
    nullable: false,
    defaultValue: "", // <-- here
    oldClrType: typeof(string),
    oldType: "varchar(25)",
    oldUnicode: false,
    oldMaxLength: 25,
    oldNullable: true);

In SQL

DECLARE @var0 sysname;
SELECT @var0 = [d].[name]
FROM [sys].[default_constraints] [d]
INNER JOIN [sys].[columns] [c] ON [d].[parent_column_id] = [c].[column_id] AND [d].[parent_object_id] = [c].[object_id]
WHERE ([d].[parent_object_id] = OBJECT_ID(N'[MyTable]') AND [c].[name] = N'Name');
IF @var0 IS NOT NULL EXEC(N'ALTER TABLE [MyTable] DROP CONSTRAINT [' + @var0 + '];');
ALTER TABLE [MyTable] ALTER COLUMN [Name] varchar(25) NOT NULL;
ALTER TABLE [MyTable] ADD DEFAULT '' FOR [Name];
GO

But instead of having the database generate a default value if null is sent, I want an exception to be thrown, so the user must input a value.

I already tried adding

[DatabaseGenerated(DatabaseGeneratedOption.None)]

or

HasDefaultValueSql(null)

or

HasDefaultValue(null)

but that does not change anything.

How can I tell EF Core to not generate a default for that column?



Solution 1:[1]

I'm not sure if Entity Framework has some tricks up it's sleeve, but with normal SQL, you would need two changes. One change of the NOT NULL status, that requires a default value, because what else should that field be set to if a null-value is encountered. And then a second change, that removes the default value from an already NOT NULL field.

So I would not be surprised if Entity Framework needed those two seperate steps, too. Just create two migrations, that should work.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nvoigt