We are trying to generate a non-nullable rowversion column on SQL Server with EF Core 3.1 using Fluent API:
public class Person
{
public int Id { get; set; }
public byte[] Timestamp { get; set; }
}
public class PersonEntityConfiguration : IEntityTypeConfiguration<Person>
{
public void Configure(EntityTypeBuilder<Person> builder)
{
builder.HasKey(p => p.Id);
builder.Property(p => p.Timestamp)
.IsRowVersion()
.IsRequired();
}
}
This works fine when the entire table is new:
public partial class PersonMigration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Persons",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Timestamp = table.Column<byte[]>(rowVersion: true, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Persons", x => x.Id);
});
}
}
However, we sometimes need to add the rowversion to an existing table. In that case, EF Core generates an invalid migration:
public partial class PersonTimestampMigration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<byte[]>(
name: "Timestamp",
table: "Persons",
rowVersion: true,
nullable: false,
defaultValue: new byte[] { });
}
}
The default value generated above will cause an exception when being applied to the database:
Failed executing DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
ALTER TABLE [Persons] ADD [Timestamp] rowversion NOT NULL DEFAULT 0x;
Microsoft.Data.SqlClient.SqlException (0x80131904): Defaults cannot be created on columns of data type timestamp. Table 'Persons', column 'Timestamp'.
Could not create constraint or index. See previous errors.
Is this a known bug in EF Core? The issue can be fixed by manually removing the defaultValue: new byte[] { }
from the migration, but is there a way of suppressing the default value from being generated using the Fluent API?