How do I change a null string to non-null int in Entity Framework 2 Core?

This is short: I have mistakenly set a property string when it should've been int. There are no constraints as this int may be optional. Even though I could make the int nullable, I rather have it a default value of zero.

Then when I try to run migrations:

Cannot insert the value NULL into column 'Edad', table 'EduPlaTools.dbo.Profesor'; column does not allow nulls. UPDATE fails. The statement has been terminated.

Which makes sense. What it's doing is updating the fields, and since many fields had "NULL", it's getting inserted. Is there a way to map those NULLs into zeroes automatically? Or do I need to do an SQL Statement?

Here's the migrationBuilder code:

   migrationBuilder.AlterColumn<int>(
                name: "Edad",
                table: "Profesor",
                nullable: false,
                oldClrType: typeof(string),
                oldNullable: true);

2 answers

  • answered 2018-12-05 20:06 Renan Barbosa

    If you are trying to change the type of a column and there are already existing records in your table, those records need to have some value specified for each of the new columns. If you have not specified a default value for the column, the database will attempt to use NULL, which will fail because the column does not allow nulls.

  • answered 2018-12-05 20:41 Jose A

    Oh no. I need to apologize. So dumb for not realizing this, Entity Framework apparently scaffolded other table with a similar property Profesor, when in fact it was Estudiante that needed change.

            migrationBuilder.AlterColumn<int>(
                name: "Edad",
                table: "Estudiante",
                nullable: false,
                oldClrType: typeof(string),
                oldNullable: true,
                defaultValue: 0);
    

    Now everything is working! Thanks everybody!