Efcore: Behaviour of bool fields with HasDefaultValue option

Created on 12 Jul 2016  路  5Comments  路  Source: dotnet/efcore

Hi. I need to clear such situation.
I have an entity Product with bool field:

public bool IsActive{ get; set; }

For that field I made such definition in my DbCOntext:

protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Product>() .Property(b => b.IsActive) .HasDefaultValue(true); }

So, if I insert the Product with "IsActive=false", the record wor this Product in DB will contain "IsActive=true".

Is it correct EF behaviour?

Because in documentation it says:

The default value of a column is the value that will be inserted if a new row is inserted but no value is specified for the column.

Because I think that "IsActive=false" is a specified value.

closed-duplicate

Most helpful comment

I found a solution from stackoverflow post for REQUIRED boolean field and default value

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
        modelBuilder.Entity<MyEntity>()
             .Property(p => p.MyRequiredBooleanField)
             .ValueGeneratedNever()
             .HasDefaultValue(false);
}

All 5 comments

@crabulik The default value is used when the property value is the CLR default for the type. False is the CLR default, so the default value is used. You probably want to use a nullable bool. Then the default will only get used if the value is null.

Reopening to consider adding a model validation that errors or warns when this scenario is hit.

There seems to be more useful information and discussion now in #7089 so closing this issue as a dupe of that one.

Hello!

This problem is still actual. If there's code like builder.Property(x => x.IsActive).HasColumnName("IsActive").HasDefaultValue(true); in entity's configuration and IsActive value equals FALSE, EF does not generate insert for this column.

Thank you!

I found a solution from stackoverflow post for REQUIRED boolean field and default value

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
        modelBuilder.Entity<MyEntity>()
             .Property(p => p.MyRequiredBooleanField)
             .ValueGeneratedNever()
             .HasDefaultValue(false);
}
Was this page helpful?
0 / 5 - 0 ratings