gpt4 book ai didi

.net - NHibernate 通过 where 选择将一张表映射到两个类

转载 作者:行者123 更新时间:2023-12-02 17:34:08 24 4
gpt4 key购买 nike

我们希望使用 NHibernate 将单个表映射到两个类。映射必须动态地取决于列的值。

这是一个简单的例子,可以让它更清楚一些:我们有一个名为 Person 的表,其中包含 id、Name 和 Sex 列。

alt text

此表中的数据应映射到 Male 类或 Female 类,具体取决于 Sex 列的值。

alt text

在伪代码中:

create instance of Male with data from table Person where Person.Sex = 'm';
create instance of Female with data from table Person where Person.Sex = 'f';

好处是我们拥有强类型域模型,以后可以避免 switch 语句。

NHibernate 可以做到这一点吗?还是我们必须首先将 Person 表映射到平面 Person 类?然后,我们必须使用自定义工厂方法,该方法采用平面 Person 实例并返回 Female 或 Male 实例。如果 NHibernate(或其他库)可以处理这个问题就好了。

最佳答案

这对于 NHibernate 来说是很常见的情况。您可以将整个类层次结构映射到单个表中。

您需要指定一个鉴别器值。

<class name="Person">
<id .../>

<discriminator column="Sex" type="string" length="1" />

<property name="Name"/>
<!-- add more Person-specific properties here -->

<subclass name="Male" discriminator-value="m">
<!-- You could add Male-specific properties here. They
will be in the same table as well. Or just leave it empty. -->
</subclass>

<subclass name="Female" discriminator-value="f">
<!-- You could add Female-specific properties here. They
will be in the same table as well. Or just leave it empty. -->
</subclass>

</class>

关于.net - NHibernate 通过 where 选择将一张表映射到两个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2964651/

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