NHibernate One-To-One Mapping

前端 未结 1 761
天涯浪人
天涯浪人 2021-02-07 21:18

I\'m new to NHibernate so have had limited exposure to mappings etc so far, and I\'ve just hit a scenario which I need some help with.

I have 2 tables:

Reviews T

相关标签:
1条回答
  • 2021-02-07 21:46

    Ayende has a good explanation for one-to-one mappings here.

    In your case the mappings should probably look like this:

    Review.hbm.xml

    <class xmlns="urn:nhibernate-mapping-2.2" name="Review" table="Reviews">
        <id name="ReviewId" unsaved-value="0">
            <column name="ReviewId"></column>
            <generator class="native" />
        </id>
    
        <property name="Title" not-null="true" />
        <property name="Descrip" not-null="true" />
        <one-to-one name="TaggedReview"
                          constrained="true"
                          foreign-key="none" 
                          class="TaggedReview" /> 
    <!-- foreign-key="none", to prevent circular reference at insert -->
    </class>
    

    TaggedReview.hbm.xml

    You will most likely need a primary key in the table, because you can't use the same column for the key and the foreign key.

    <class xmlns="urn:nhibernate-mapping-2.2" name="TaggedReview" table="TaggedReviews">
        <id name="SomeOtherId">
            <column name="SomeOtherId"></column>
            <generator class="native"/>
        </id>
        <many-to-one name="Review" 
                     unique="true"
                     class="Review"> <!-- Use many-to-one for a foreign key -->
          <column name="ReviewId" />
        </many-to-one>
        <property name="TaggedReviewDescrip" not-null="true" />
    </class>
    

    If you cannot or do not want to change the db, you can take a look at NHibernate mapping - one-to-one (or one-to-zero).

    0 讨论(0)
提交回复
热议问题