NHibernate一对一映射 - 奇怪的连接?

时间:2011-03-17 01:03:58

标签: nhibernate fluent-nhibernate mapping one-to-one

我在NHibernate一对一映射方面遇到了一些问题。我正在使用Fluent Nhibernate,并在我的博客文章中添加了我的映射:http://brunoreis.com/tech/fluent-nhibernate-hasone-how-implement-one-to-one-relationship/

表格的信息:

dbo.Store
---------
Id : int

dbo.CheckoutSettings
---------
StoreId :int (FK to dbo.Store.Id)

以下是一些HBM:

  <class xmlns="urn:nhibernate-mapping-2.2" schema="Management" mutable="true" name="Store" table="Streo">
    <id name="Id" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" unsaved-value="0">
      <column name="Id" />
      <generator class="native" />
    </id>
<one-to-one cascade="all" class="CheckoutSettings" constrained="false" name="CheckoutSettings" /> 
  </class>

  <class xmlns="urn:nhibernate-mapping-2.2" schema="Management" mutable="true" name="CheckoutSettings" table="CheckoutSettings">
    <id name="StoreId" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="StoreId" />
      <generator class="foreign">
        <param name="property">Store</param>
      </generator>
    </id>
    <one-to-one class="Store" foreign-key="FK_CheckoutSettings_StoreId" name="Store" />
</class>

事情似乎在本地工作,但在我们的测试服务器上,我得到了错误保存,例如意外行数:0(预期:1)。在加载过程中,我看到奇怪的sql连接:

select  (columns)
from    checkoutsettings c0
  left outer join store s on keys
  left outer join checkoutsettings c1 on keys
where c0.Storeid = id 

这不会返回任何内容,因为结帐设置可能没有商店的行。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您应该将CheckoutSettings与Store的关系映射为多对一,并将unique设置为true:

<many-to-one class="Store" name="Store" unique="true" column="StoreId" />

从Store到CheckoutSettings使用property-ref:

一对一
<one-to-one cascade="all" class="CheckoutSettings" constrained="false" property-ref="Store" name="CheckoutSettings" />

您还应该注意,因为Store实体中的CheckoutSettings属性可以为null,所以当您获取商店时,NHibernate会生成到CheckoutSettings表的连接。这是因为NHibernate必须知道数据库中已获取的存储的CheckoutSettings,以便它可以将CheckoutSettings属性设置为null(如果没有)。

答案 1 :(得分:0)

经过进一步调查后,我们发现我们在插入和更新时遇到了一些奇怪的事情。一旦我们解决了这个问题,我们就可以进行更改以解决问题。