You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过NHibernate XML映射IDictionary集合?

NHibernate XML映射IDictionary<int, Bar>的实现方案

针对你要映射IDictionary<int, Bar>的需求,下面是NHibernate XML映射的具体实现:

Foo实体的映射文件

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="你的程序集名称" namespace="你的命名空间">
  <class name="Foo" table="Foo">
    <!-- 需添加Foo的主键映射,示例如下 -->
    <id name="Id" column="FooId" type="Int32">
      <generator class="identity" />
    </id>

    <!-- 核心IDictionary集合映射 -->
    <map name="Bars" table="FooBar" lazy="true" cascade="all">
      <!-- 关联Foo实体的外键列 -->
      <key column="FooId" not-null="true" />
      <!-- 字典的int类型键,对应中间表的存储列 -->
      <index column="BarKey" type="Int32" />
      <!-- 字典值关联Bar实体 -->
      <one-to-many class="Bar" />
    </map>
  </class>
</hibernate-mapping>

关键节点说明

  • <map>:专门用于映射IDictionary类型集合,table指定关联中间表的名称(示例用FooBar)。
  • <key>:定义Foo实体在中间表中的外键列,关联Foo的主键。
  • <index>:对应字典的key(即你的int类型键),column是中间表存储该键的列名,type指定键的数据类型。
  • <one-to-many>:声明字典的值为Bar实体,关联Bar的映射配置。

Bar实体的映射文件

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="你的程序集名称" namespace="你的命名空间">
  <class name="Bar" table="Bar">
    <id name="Id" column="BarId" type="Int32">
      <generator class="identity" />
    </id>
    <property name="Name" column="Name" type="String" length="255" />
  </class>
</hibernate-mapping>

额外注意事项

  • 中间表FooBar需包含三个列:FooId(关联Foo主键)、BarKey(存储字典int键)、BarId(关联Bar主键),推荐将FooId+BarKey设为联合主键,更符合关联场景。
  • cascade属性可控制级联操作(如all表示所有操作级联到Bar),lazy属性控制集合的延迟加载行为,可根据业务需求调整。

内容的提问来源于stack exchange,提问作者TP95

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 19:02:35