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.
The default value of a nullable value type represents null , that is, it's an instance whose Nullable<T>. HasValue property returns false .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With