The default value of bool is false when null in a database with Entity Framework 4.1. Code first

How to set the default value when the value (bit) in the database is set to NULL. Right now I am getting a message that it cannot be NULL when loading bool from the database.

Thanks.

+6
null boolean bit default
source share
3 answers

Your model must match the database — if the database can be NULL, you must use the nullable bool in your model, however you can rewrite the setter for this property in your model to turn NULL to false:

public class Foo { private bool _bar; public bool? Bar { get { return _bar; } set { if (!value.HasValue) { _bar = false; } else _bar = value.Value; } } } 

Ideally, you should avoid this situation and set the default value in the database column - then you will not need this workaround.

+6
source share

When adding a migration for changes to the database, update the migration class to set the default value before updating the database:

 AddColumn("Jobs", "IsAdvertisingRequired", c => c.Boolean(nullable: false, defaultValueSql: "0")); 

This will translate into the following SQL:

 ALTER TABLE [Jobs] ADD DEFAULT ((0)) FOR [IsAdvertisingRequired] GO 
+5
source share

You can change my answer from Is it possible by default to use the DateTime field for GETDATE () with Entity Framework migrations? to set the default valueValue / defaultValueSql to false. It uses a wrapper class that implements MigrationCodeGenerator and then modifies MigrationOperations (CreateTableOperation / AddColumnOperation) to set the DefaultValueSql properties for DateTime if they are not null.

+1
source share

All Articles