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

如何用C#将Dictionary映射到Hibernate映射文件?

问题解答

选Map还是Set/List?

你的属性是Dictionary<string, int>,属于键值对集合,NHibernate里对应的就是<map>元素——Set是无重复的无序集合,List是有序集合,都不匹配Dictionary的键值结构,所以必须用<map>。

正确的映射配置

你之前的配置有语法错误,比如<property="value"写法不对,而且index没指定类型,导致报错。下面是能正常工作的配置:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="你的程序集名称"
                   namespace="你的命名空间">
  <class name="SomeClass" abstract="true" table="SomeClass">
    <!-- Guid主键的正确配置,要指定生成策略 -->
    <id name="Id" column="Id" type="Guid">
      <generator class="guid.comb"/>
    </id>
    <property name="Description" column="Description" type="String"/>
    
    <!-- Dictionary<string, int>的映射 -->
    <map name="DictionaryInClass" table="SomeClass_Dictionary" lazy="true">
      <!-- 关联主表的外键列 -->
      <key column="SomeClassId" not-null="true"/>
      <!-- 映射字典的键(string类型),指定列名和类型 -->
      <index column="DictKey" type="String" length="255"/>
      <!-- 映射字典的值(int类型),用element因为是简单类型 -->
      <element column="DictValue" type="Int32" not-null="true"/>
    </map>
  </class>
</hibernate-mapping>

配置细节说明

  • <key>:用来关联主表SomeClass的外键列SomeClassId,必须设为not-null="true",保证数据完整性。
  • <index>:对应Dictionary的键,必须指定type="String"告诉NHibernate键的类型,column是存储键的列名,你可以自己改,注意别用数据库关键字。
  • <element>:对应Dictionary的值,因为是int这种简单值类型,所以用<element>;如果值是自定义类才用<composite-element>,这也是你之前用composite-element报错的原因——Dictionary的值是int,不是复杂对象。
  • table:指定单独存储字典数据的表,比如SomeClass_Dictionary,这个表会自动生成三列:SomeClassId(外键)、DictKey、DictValue。

你之前的错误点

  1. <property="value"是语法错误,简单值类型要用<element>。
  2. <index>没指定类型,NHibernate无法识别键的类型,必须加type="String"。
  3. 主键Id之前只写了<property name="Id"/>,Guid主键需要用<id>标签配置,还要指定生成策略,不然会出主键相关的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 13:49:52