Skip to content

Adding a required field to entity with without explicitly specifying a default value produces migrations that are inconsistent with model #27084

@ntziolis

Description

@ntziolis

When adding a new required field without a default value a default value. And adding creating a migration afterwards the up migration contains:

  • an "add column step"
    • with the column marked as non nullable (this is correct)
    • but it also sets a default value (it seems to be the default value of the type (int = 0, datetime = minvalue etc.)
      • again nowhere in the model a default value was specified

After executing this migration the result is:

  • There is a default value set in the db
  • Without it being reflected in the code (entity model / snapshot)

From my pov there are 2 options to fix this:

  • option 1
    • ef migrations add fails when no default value is explicitly specified
    • this does mean if the column should not have a default value beyond the initial intend of filling nulls in the existing data
    • we need to remove the default value and add another migration
  • option 2
    • when executing ef migrations add the resulting migration should include 2 steps for each column
    • add column (with default value)
    • and alter column (removing the default value)
    • This would only be done if the user did not explicitly specify a default value for the new column

I do prefer the second option as it creates less unnecessary migrations, that said I can easily think of situations where it will be problem that ef just decides what the default value for existing data should be. Hence I would suggest to output a warning when migrations are created similar to danger of data loss. This would give the user the ability to double check the migration and adjust the "temporary" default value if needed.

Include provider and version information

EF Core version: 6.01
Database provider: I'm assuming this will apply to all relational providers
Target framework: .NET 6.0
Operating system: Windows
IDE: 2022 latest

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions