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

advertisements

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?


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;
        }
    }
}