What is the code-first approach to set the default value of a database column in entity framework core?
Attempt #1: Using the DefaultValue
attribute on the model doesn't seem to work
[DefaultValue(true)]
public bool ShowInReports { get; set; }
After running the migration, the following code is generated by dotnet ef version 5.0.1:
migrationBuilder.AddColumn<bool>(
name: "ShowInReports",
table: "ParametersUsed",
nullable: false,
defaultValue: false);
Attempt #2: trying to define the value in OnModelCreating
doesn't recognize the function:
modelBuilder.Entity<TableName>()
.Property(t=> t.ShowInReports)
.HasDefaultValue(true);
Error: 'PropertyBuilder<bool>' does not contain a definition for 'HasDefaultValue' and no accessible extension method 'HasDefaultValue' accepting a first argument of type 'PropertyBuilder<bool>' could be found (are you missing a using directive or an assembly reference?)
Reposting my comment, since it seems to be the answer, too.
You need to add the Microsoft.EntityFrameworkCore.Relational package for the HasDefaultValue
extension method to be available.
As for the DefaultValue
attribute, I'm not convinced it can be used with EF Core, or with EF in general. I might be wrong, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With