最近一段时间再看nhibernate相关的东西,再开发的时候遇到了一个困扰了很久的问题:
背景:TbAgent与TbSend是1对多的情况,关系:TbAgent.Mobilephone = TbSend.RecPhone 这2个关系都是非主键的。
最后使用property-ref属性解决。详细的配置如下:
TbAgent的配置文件:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="Sample.Model.TbAgent,Sample.Model" table="Tb_Agent" lazy="true">
<id name="Id" column="Id" type="Int32" unsaved-value="0">
<generator class="native"/> </id>
<property column="AgentId" type="Int32" name="AgentId" not-null="true" />
<property column="AgentName" type="String" name="AgentName" not-null="true" length="1024" />
<property column="ContactName" type="String" name="ContactName" not-null="true" length="1024" />
<property column="Tel" type="String" name="Tel" length="1024" />
<property column="MobilePhone" type="String" name="MobilePhone" not-null="true" length="1024" />
<property column="Address" type="String" name="Address" length="1024" />
<property column="Comment" type="String" name="Comment" length="1073741823" />
<bag name="TbSend" inverse="true" lazy="true">
<key column="RecPhone" property-ref="MobilePhone"/>
<one-to-many class="Sample.Model.TbSend,Sample.Model" not-found="ignore"/>
</bag>
</class>
</hibernate-mapping>
TbSend的配置:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="Sample.Model.TbSend,Sample.Model" table="Tb_Send" lazy="false">
<id name="Id" column="Id" type="Int64" unsaved-value="0"> </id>
<property column="RecPhone" type="String" name="RecPhone" not-null="true" length="1073741823" />
<property column="SendTag" type="Boolean" name="SendTag" not-null="true" />
<property column="Content" type="String" name="Content" not-null="true" length="1073741823" />
<property column="SendTime" type="DateTime" name="SendTime" not-null="true" />
<property column="ToUser" type="Boolean" name="ToUser" not-null="true" />
<property column="ToAgent" type="Boolean" name="ToAgent" not-null="true" />
<property column="ToHyundai" type="Boolean" name="ToHyundai" not-null="true" />
<many-to-one name="TbAgent" column="RecPhone" property-ref ="MobilePhone" class="Sample.Model.TbAgent,Sample.Model">
</many-to-one>
</class>
</hibernate-mapping>
网上搜了一下对这个的解释:
property-ref:指定关联类的一个属性,这个属性将会和本外键相对应。如果没有指定,会使用对方关联类的主键(可选).property-ref属性只应该用来对付老旧的数据库系统,可能出现外键指向对方关联表的是个非主键字段(但是应该是一个惟一关键字)的情况。这是一种十分丑陋的关系模型。比如说,假设Product类有一个惟一的序列号,它并不是主键;