我有一个Account表和一个Transaction表,没有从Transaction表到Account表的外键引用"遗留原因"。 NHibernate Account表的映射XML如下所示:
<class name="Account" table="[tblAccount]" lazy="true">
<id name="ID" column="ID" type="Int32">
<generator class="native" />
</id>
<version name="NHVersion" column="[NHVersion]" unsaved-value="0" />
<property name="AccountNumber" column="[AccountNumber]" type="String" not-null="true" length="30" />
<property name="FormattedAccountNumber" column="[FormattedAccountNumber]" type="String" not-null="true" length="30" />
<property name="Title" column="[Title]" type="String" not-null="true" length="30" />
<many-to-one name="AccountCode" column="tblAccountCodeID" class="AccountCode" cascade="none" />
<one-to-one name="AccountSegment" cascade="all" class="AccountSegment" property-ref="Account" />
<bag name="Categories" table="tblAccountCategory" lazy="true" inverse="false">
<key column="tblAccountID" />
<many-to-many class="Category" column="tblCategoryID" />
</bag>
</class>
Transaction表的映射XML是:
<class name="Transaction" table="[tblTransaction]" lazy="true">
<id name="ID" column="ID" type="Int32">
<generator class="native" />
</id>
<version name="NHVersion" column="[NHVersion]" unsaved-value="0" />
<property name="GLAccount" column="[GLAccount]" type="String" not-null="true" length="30" />
<property name="Description" column="[Description]" type="String" not-null="true" length="60" />
<property name="Amount" column="[Amount]" type="Decimal" not-null="true" />
</class>
可以使用GLAccount
列查询给定帐户的事务表行。以下SQL有效:
select act.FormattedAccountNumber, act.Title, trn.Date, trn.Amount
from tblAccount act
left join tblTransaction trn on act.AccountNumber = trn.GLAccount
where act.AccountNumber = '011020'
如何定义帐户交易的映射?似乎没有办法为每个表指定列名。也许使用where
?我看了question and answer,但它似乎并不适用于我的情况。
答案 0 :(得分:1)
NHibernate内置解决方案适用于没有主键的场景:
FROM tblAccount act
LEFT JOIN tblTransaction trn
ON act.AccountNumber = trn.GLAccount
这就是property-ref
魔法。
<class name="Account" table="[tblAccount]" lazy="true">
...
<!-- THE property -->
<property name="AccountNumber" column="[AccountNumber]" type="String" not-null="true"/>
<!-- collection referenced by THE property -->
<bag name="Transactions" lazy="true" inverse="false">
<!-- key column of a target table -->
<!-- property-ref of our table -->
<key column="GLAccount" property-ref="AccountNumber" />
<one-to-many class="Transaction" />
</bag>
这是父母,下面是一个孩子(多对一使用与参考相同的属性)
<class name="Transaction" table="[tblTransaction]" lazy="true">
...
<property name="GLAccount" column="[GLAccount]" type="String" not-null="true"/>
<many-to-one name="Account" column="[GLAccount]" property-ref="AccountNumber" />
...
property-ref
属性仅应用于映射旧数据,其中外键是指除主键之外的关联表的唯一键。这是一个丑陋的关系模型。例如,假设Product类具有唯一的序列号,而不是主键。 (unique属性使用SchemaExport工具控制NHibernate的DDL生成。)