如何使EF将空字符串保留为NULL? [英] How do I get EF to persist empty strings as NULL?

查看:475
本文介绍了如何使EF将空字符串保留为NULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的域中,NULL和空字符串之间没有重要区别。如何让EF忽略两者之间的区别,并始终将空字符串保持为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?

推荐答案

空字符串不是字符串属性的默认值,这意味着您的代码在某处设置空字符串。在这种情况下,您有责任处理。

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.

如果您使用POCO代码,可以使用自定义设置器:

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

这篇关于如何使EF将空字符串保留为NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆