Home > front end >  Entity Framework Core Database first sets property nullable
Entity Framework Core Database first sets property nullable

Time:09-27

Iam working with Entity Framework Core and a legacy database.

When migrating the database to my models, Iam using this script:

Scaffold-DbContext "Server=abc\SQLEXPRESS;Database=mydatabase;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Everything works fine but the script is creating a class with a property that is nullable:

public bool? Active { get; set; }

But my database has a field, which is "Not Null"

The migration script is also creating a context file:

entity.Property(e => e.Active)
                    .IsRequired()
                    .HasColumnName("active")
                    .HasDefaultValueSql("((1))");

Why is the migrated field "Active" a nullable bool? and not just a bool in my C# models?

CodePudding user response:

I think it's because you have a default value. In this case, EF accepts null value because the DB server puts the default one. In my experience, "Not null" field without default value render non nullable bool field in my model.

  • Related