Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove the default constraint from migration script

I have a migration script and I want to remove the default value from the column please help

 migrationBuilder.AddColumn<bool>(
              name: "IsExternalLink",
              table: "Link",
              nullable: false,
              defaultValue: 0);

I want to alter the column and remove the default value.

I tried altering column like this :

  migrationBuilder.AlterColumn<bool>(
                  name: "IsExternalLink",
                  table: "Link");

but this does not remove the default value

like image 234
Harsha Mullangi Avatar asked Jun 14 '26 05:06

Harsha Mullangi


2 Answers

If you want to remove the DEFAULT value of a column you must define the oldDefaultValue.

// drop default
migrationBuilder.AlterColumn<bool>(
                name: "col",
                table: "my_table",
                oldDefaultValue: true, <-- THIS must be defined!
                defaultValue: null);

// Resulting Query: ALTER TABLE my_table ALTER COLUMN col DROP DEFAULT

Make also sure that the <type>, name (..) are also correct, because EfCore won't complain anything if your written AlterColumn statement is garbage.


Furthermore if your table already contains rows and you would like to add a new column with none DEFAULT, do the following:

// add column WITH default for existing rows
migrationBuilder.AddColumn<bool>(
                name: "col",
                table: "my_table",
                type: "boolean",
                nullable: false,
                defaultValue: true);

// drop default for new entries
migrationBuilder.AlterColumn<bool>(
                name: "col",
                table: "my_table",
                oldDefaultValue: true,
                defaultValue: null);
like image 163
FireEmerald Avatar answered Jun 15 '26 18:06

FireEmerald


Booleans are value types, You need to specify a value for them unless you make a nullable boolean as @StepUp has mentioned. You can read more abouut value types here

However if you want to have a default value for IsExternal different then zero you can set it in your POCO class

public boolean IsExternalLink{ get; set; } = true; // To wahtever default value you choose
like image 41
Shahid Manzoor Bhat Avatar answered Jun 15 '26 20:06

Shahid Manzoor Bhat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!