EF Core power tools generate nullable Boolean
Asked Answered
D

2

9

I am using EF Core Power Tools version 2.4.0 with Miccrosoft.EntifyFrameworkCore.SqlServer version 2.2.6

I have SQL table column IsActive defined as [IsActive] [bit] NOT NULL
I use EF Core Power Tool's reverse engineering to generate entities and DB Context.

ISSUE
The tool generate null-able Boolean property instead of just Boolean

public bool? IsActive { get; set; }

the corresponding DBContext's OnModelCreating method

modelBuilder.Entity<Scenario>(entity =>
            {
                entity.Property(e => e.ScenarioID).HasColumnName("ScenarioID");

                entity.Property(e => e.IsActive)
                    .IsRequired()
                    .HasDefaultValueSql("((1))");

}
Deva answered 26/2, 2020 at 17:9 Comment(0)
N
6

EF Core uses the CLR default value to determine whether to use the SQL default.

With nullable:

  • null ➡ 1 (via DEFAULT)
  • false ➡ 0
  • true ➡ 1

Without nullable:

  • false ➡ 1 (via DEFAULT)
  • true ➡ 1

Without nullable, there would be no way to insert a 0!

Another alternative is to just remove HasDefaultValueSql and use non-nullable:

  • false ➡ 0
  • true ➡ 1
Nightstick answered 26/2, 2020 at 18:25 Comment(5)
don't understand Without nullable, there would be no way to insert a 0! you can insert 0 in not null columnDeva
Correct, you can outside of EF Core. Inside EF Core, however, a non-nullalbe bool has two values--false and true--and EF Core uses the CLR default (false) to indicate that you want to use the SQL default (1). There would be no way to tell EF to insert 0.Nightstick
Note that it's sill marked as IsRequired--you can't actually save NULL values to the database. It just means that if you save a new entity without setting a value, the SQL default (1) will be used.Nightstick
@Nightstick I wonder one thing about this.. why not have a column that is X BIT NOT NULL DEFAULT 1 be mapped as public bool X { get; set; } = true; then you can save a 0 by setting it false but by default it is inited as true so the C# apes the SQL behavior? (Why do we need a way to say to EF "i want to use the DB default here" vs copying DB defaults to C#? OK, it doesn't allow the DBA to alter them without recompiling C# but that seems like asking for trouble anyway.. Could allow in other ways than nullabools too (isSet=false bool that trues upon set{} or do bool?->bool in get{})Pirogue
@CaiusJard Great minds think alike. See #15070 (comment)Nightstick
L
3

You can disable this behavior in the latest release of EF Core Power Tools, so the default is ignored

Landwaiter answered 11/5, 2021 at 14:8 Comment(1)
Thanks! My extension was disabled upon updating but got it figured out. For others wondering, the setting for this is to check "Remove SQL default from bool columns" under Reverse Engineer > Advanced.Rhythmist

© 2022 - 2024 — McMap. All rights reserved.