Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 772
Andreas Avatar asked Apr 06 '11 13:04

Andreas


People also ask

What is the default value of a nullable bool?

The default value of a nullable value type represents null , that is, it's an instance whose Nullable<T>. HasValue property returns false .

How do I change the default boolean value?

Use the create() or update() methods to specify the value of the new property as its default value, that is, false for boolean or 0 for integer. The property value should get updated successfully.

Can bool return null?

A boolean in . NET is a struct hence is a value type and can not be null. By definition a bool value is either true or false ; binary the basic building blocks of computing.


1 Answers

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.

like image 69
BrokenGlass Avatar answered Sep 25 '22 05:09

BrokenGlass