8

How can I set the default value when a value (bit) in the database is set to NULL. Right now I'm getting a error telling me that it can't be NULL when loading a bool from the database.

Thanks.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
Andreas
  • 1,311
  • 5
  • 24
  • 39

3 Answers3

6

When you add a migration for your database changes, 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
David Clarke
  • 12,888
  • 9
  • 86
  • 116
6

Your model has to match the database - if the database may have a NULL value you should use a nullable bool in your model - you can however overwrite the setter for that property in your model to turn a NULL into a false value:

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 a default value in your database column - then you don't need this workaround.

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
1

You could modify my answer from Possible to default DateTime field to GETDATE() with Entity Framework Migrations? to set the defaultValue/defaultValueSql to false. It uses a wrapper class that implements MigrationCodeGenerator and then modifies the MigrationOperations (CreateTableOperation/AddColumnOperation) to set the DefaultValueSql for DateTime properties if they are not null.

Community
  • 1
  • 1
JonnySchnittger
  • 389
  • 3
  • 7