Bug #99501 Alter Column migration script sets column to NOT NULL when column should be NULL
Submitted: 10 May 2020 13:51 Modified: 10 Aug 2022 21:15
Reporter: Bronze Brown Email Updates:
Status: Duplicate Impact on me:
None 
Category:Connector / NET Severity:S2 (Serious)
Version:MySql.Data.EntityFrameworkCore 8.0.20 OS:Any
Assigned to: CPU Architecture:Any
Tags: alter column, Connector/Net, EntityFrameworkCore, MySql.Data.EntityFrameworkCore

[10 May 2020 13:51] Bronze Brown
Description:
There is an error with MySQL Generation Script with Entity Framework Code First Methodology This error was encountered using Microsoft.EntityFrameworkCore.Relational (3.1.1 - 3.1.3) and MySql.Data.EntityFrameworkCore (8.0.20)

The following Migration Script 

protected override void Up(MigrationBuilder migrationBuilder) { 
        migrationBuilder.DropForeignKey( 
            name: "FK_patient_agency_AgencyId", 
            table: "patient");

        migrationBuilder.AlterColumn<int>(
            name: "AgencyId",
            table: "patient",
            nullable: true,
            oldClrType: typeof(int),
            oldType: "int");

        migrationBuilder.AddForeignKey(
            name: "FK_patient_agency_AgencyId",
            table: "patient",
            column: "AgencyId",
            principalTable: "agency",
            principalColumn: "Id",
            onDelete: ReferentialAction.Restrict);
    }
Produced the following SQL, I have marked line with the generation error

ALTER TABLE patient DROP CONSTRAINT FK_patient_agency_AgencyId;

ALTER TABLE patient MODIFY AgencyId int NOT NULL; <-- Error is here. "NOT" should not exist.

ALTER TABLE patient ADD CONSTRAINT FK_patient_agency_AgencyId FOREIGN KEY (AgencyId) REFERENCES agency (Id) ON DELETE RESTRICT;

INSERT INTO __EFMigrationsHistory (MigrationId, ProductVersion) VALUES ('20200508195058_Test FK nullable issue', '3.1.3');

How to repeat:
Reproduction Steps.

1) Create a model where the following is true: "Object A" has a required navigation property to "Object B"
2) Have Entity Framwork create a migration.
3) Remove the required attribute from the navigation property created above
4) Create a migration script. <-- Error occurs on this step
This error only occurs when altering a column.

Suggested fix:
when AlterColumn is called by the Migration Builder and nullable is set to true. Generated Column should be set to NULL.
[10 Aug 2022 21:15] Daniel Valdez
Duplicate of Bug #96913