简体   繁体   中英

nhibernate : One to One mapping

I have the following map. I wish to map BasketItem to the class "Product". So basically when i iterate thru the basket i can get the product name

<class name="BasketItem" table="User_Current_Basket">
<id name="Id" type="Int32" column="Id" unsaved-value="0">
<generator class="identity"/>
</id>
<property name="ProductId" column="Item_ID" type="Int32"/>
  <one-to-one   name="Product"
        class="Product"></one-to-one>
</class>

How do specifiy that product should match BasketItem.ProductId with Product.Id

Also i've read that i should avoid one-to-one and just use one-to-many? If i was to do that how do i ensure i just get one product and not a collection.

// EDIT

select * from BasketItem
inner join Products on BasketItem.Item_ID = Products.Item_ID

How do specifiy that product should match BasketItem.ProductId with Product.Id

Your BasketItem should hold a Product at the object level, not the ProductId . And the mapping should be:

<class name="BasketItem" table="User_Current_Basket">
  <id name="Id" type="Int32" column="Id" unsaved-value="0">
    <generator class="identity"/>
  </id>
  <one-to-one name="Product" class="Product"/>
</class>

Also i've read that i should avoid one-to-one and just use one-to-many? If i was to do that how do i ensure i just get one product and not a collection.

If you want to be able to lazy-load the Product , prefer a "fake" many-to-one:

<class name="BasketItem" table="User_Current_Basket">
  <id name="Id" type="Int32" column="Id" unsaved-value="0">
    <generator class="identity"/>
  </id>
  <many-to-one name="Product" class="Product"/>
</class>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM