开发者

NHibernate one to one mapping - weird joins?

I'm having some problems with NHibernate one to one mapping. I'm using Fluent Nhibernate, and basd my mappings on this blog post: http://brunoreis.com/tech/fluent-nhibernate-hasone-how-implement-one-to-one-relationship/

A snippit of the tables:

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

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

Here's some HBMs:

  <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>

Things seem to work locally, but on our test server I get errors saving, such as Unexpected row count: 0开发者_StackOverflow中文版 (expected: 1). Also during loading I see odd sql joins:

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

And this doesn't return anything as checkout settings may not have a row for the store.

Any ideas?


You should map the relation from CheckoutSettings to Store as many-to-one with unique set to true:

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

From Store to CheckoutSettings use one-to-one with property-ref:

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

You should also note that because the CheckoutSettings-property in the Store entity can be null NHibernate generates a join to CheckoutSettings table when you fetch a store. This is because NHibernate must know is there CheckoutSettings for the fetched store in the database so that it can set the CheckoutSettings-property null if there isn't one.


After further investigation we discovered that we had some triggers doing odd things on insert and update. Once we figured this out, we were able to make changes that resolved the issue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜