You need to enable JavaScript to run this app. 如何在NHibernate中为模型添加关联表主键属性且无需修改表结构
优惠活动
大模型
产品
解决方案
定价
更多

如何在NHibernate中为模型添加关联表主键属性且无需修改表结构

NHibernate 映射同列只读Id属性方案

修改步骤

1. 调整模型类

在Configuration.cs中新增OrganisationId属性,属性类型和可空性要和Organisation表的主键完全匹配:

//Configuration.cs  (Model Class)
public virtual Organisation Organisation { get; set; }
// 新增属性,类型根据Organisation主键实际类型调整,比如主键是Guid就换成Guid?
public virtual int? OrganisationId { get; set; }

2. 调整hbm映射文件

在原有many-to-one节点补充column属性指定存量外键的实际字段名,再新增一个只读的property节点映射同一个字段:

//Configuration.hbm.xml
<many-to-one name="Organisation"
                 class="Organisation"
                 <!-- 替换为你数据库Configuration表中实际的外键字段名,部分命名规范下可能是Organisation_Id -->
                 column="OrganisationId" 
                 not-null="false"
         foreign-key="FK_ConfigurationItem_Organisation"
         unique-key="UniqueConfigurationItemName"/>
<!-- 新增只读属性映射,column和上面的many-to-one配置保持一致 -->
<property name="OrganisationId" column="OrganisationId" insert="false" update="false" />

注意事项

  • 两个映射节点的column值必须和数据库存量外键字段完全一致,无需新增表字段
  • insert="false"和update="false"为必填配置,告知NHibernate该属性仅用于读取,不会参与写入操作,避免多映射同列的写入冲突
  • 原有Organisation关联的所有存量逻辑完全不受影响,仅新增了无需加载关联对象即可读取外键Id的能力

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 19:45:00