gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:21:03 24 4
gpt4 key购买 nike

有谁知道让 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 的值。这实际上取决于手头的情况。

关于c# - NHibernate:将默认值视为 null 的简单方法(反之亦然),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3098400/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com