Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get EF to persist empty strings as NULL?

In my domain, there's no important distinction between NULL and an empty string. How do I get EF to ignore the difference between the two and always persist an empty string as NULL?

like image 314
Josh Kodroff Avatar asked Dec 28 '22 19:12

Josh Kodroff


1 Answers

Empty string is not default value for string property so it means your code is setting empty strings somewhere. In such case it is your responsibility to handle it.

If you are using code first with POCOs you can use custom setter:

private string _myProperty;
public string MyProperty
{
    get { return _myProperty; }
    set
    {
        if (value == String.Empty)
        {
            _myProperty = null;
        }
        else
        {
            _myProperty = value;
        }
    }
}
like image 139
Ladislav Mrnka Avatar answered Jan 18 '23 19:01

Ladislav Mrnka