EF Core power tools generate nullable Boolean

Viewed 2092

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))");

}
2 Answers

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

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

Related