Andreas
Andreas

Reputation: 1311

Default bool to false when null in database with Entity Framework 4.1 Code First

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.

Upvotes: 8

Views: 12614

Answers (3)

Jay
Jay

Reputation: 389

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.

Upvotes: 1

David Clarke
David Clarke

Reputation: 13246

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

Upvotes: 6

BrokenGlass
BrokenGlass

Reputation: 160852

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.

Upvotes: 6

Related Questions