Jose A
Jose A

Reputation: 11077

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

Upvotes: 1

Views: 2412

Answers (2)

Jose A
Jose A

Reputation: 11077

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!

Upvotes: 1

Renan Barbosa
Renan Barbosa

Reputation: 1084

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.

Upvotes: 1

Related Questions