Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Entity Framework Core Database first sets property nullable

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading