Skip to main content
 首页 » 编程设计

c#之NHibernate:将默认值视为 null 的简单方法(反之亦然)

2024年02月24日21pander-it

有谁知道让 NHibernate 将值类型的默认值作为 null 插入数据库的快速方法吗?

例如:

public class Foo 
{ 
    public int SomeProperty { get; set; } 
} 

默认情况下,int 为 0。当它进入数据库时​​,我希望它以 null 的形式进入。 我知道我可以通过将 SomeProperty 更改为可为空的 int 来做到这一点,但也许还有另一种方法? 我也知道我可以使用 IUserType 来做到这一点,但是有没有一种简单的方法来构建可以普遍用于所有值类型的用户类型?

请您参考如下方法:

这不是让 NHibe 将 0 转换为 null 和反之亦然的简单方法,而是一种替代建议(在您的情况下可能正确,也可能不正确)。

Imo,使用默认值表示 null 是一种反模式;也许你同意。我认为您正在尝试将一些遗留代码与适当的数据库连接起来;对吗?

如果您可以控制要映射的业务类(Foo 类),那么我建议公开一个可空版本的 SomeProperty 以便继续使用:

public class Foo 
{ 
    /// for new code, and for mapping to the database: 
    public int? SomeProperty_new {get;set;} 
 
    /// for legacy code only.  Eventually, refactor legacy code to use SomeProperty_new instead, and just remove this needless property. 
    [Obsolete("This uses default value to mean null.  Use SomeProperty_new instead.")] 
    public int SomeProperty_old 
    {  
        get  
        { 
            if (SomeProperty_new == null) 
                return 0; 
            else 
                return SomeProperty_new; 
        } 
        set { /* convert from 0 to null if necessary and set to SomeProperty_new.*/ } 
    } 
} 

不过,您会想要比 SomeProperty_new 和 SomeProperty_old 更好的名称。

另一方面,如果 0 永远不是有效值(除了表示 null),您可以改为让 DB 使用不可为 null 的值。这实际上取决于手头的情况。