efcore: AddColumn migrations created with bad default
Hope I’m not reporting a dup here.
Testing with SqlServer, I’ve added this property to my model:
builder.Entity<Blog>().Property(b => b.SomeProp).ValueGeneratedOnAdd();
Generating a migration creates the following code:
migrationBuilder.AddColumn<int>(
name: "SomeProp",
table: "Blogs",
nullable: false,
defaultValue: 0)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
Note the defaultValue: 0, which I didn’t specify in the model in any way. Note also that if the column is defined when creating the table, the correct CreateTable migration is generated:
SomeProp = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
This causes an issue with Npgsql (https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/68) since the default value is examined in the migration decision process.
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Comments: 28 (21 by maintainers)
@rowanmiller, note the discrepancy between what happens if the non-nullable column is present when the table is created, and when it’s added later (i.e. between the CreateTable migration and the AddColumn migration) - in the first case there’s no default, in the second there is. This is the part that bothers me most; if you always set the CLR default as the column default it would at least be consistent (although still wrong IMHO).
Again, I get the reasoning behind the default - when adding a column to an existing table there’s the issue of existing rows, which doesn’t exist when creating a new table. But that seems to be a detail; it seems that the database schema for a given model should be the same regardless of the history/migration path taken to reach it.