Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core - DefaultValue(true) attribute not working

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?)

like image 465
Ovi Avatar asked Dec 14 '20 22:12

Ovi


1 Answers

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.

like image 172
Riwen Avatar answered Oct 18 '22 13:10

Riwen