【问题标题】:nhibernate : One to One mappingnhibernate:一对一映射
【发布时间】:2010-05-15 13:26:06
【问题描述】:

我有以下地图。我希望将 BasketItem 映射到“产品”类。所以基本上当我遍历篮子时,我可以获得产品名称

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

如何指定该产品应将 BasketItem.ProductId 与 Product.Id 匹配

我也读过我应该避免一对一而只使用一对多?如果我要这样做,我如何确保我只得到一个产品而不是一个系列。

// 编辑

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

【问题讨论】:

    标签: c# .net nhibernate nhibernate-mapping orm


    【解决方案1】:

    如何指定该产品应将 BasketItem.ProductId 与 Product.Id 匹配

    您的BasketItem 应该在对象级别包含Product,而不是ProductId。映射应该是:

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

    我也读过我应该避免一对一而只使用一对多?如果我要这样做,我如何确保我只得到一个产品而不是一个系列。

    如果您希望能够延迟加载 Product,请选择“假”多对一:

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

    【讨论】:

    • 谢谢,关于一对一。 “BasketItem”如何知道它必须匹配 basketItem.ProductId = product.Id 上的所有产品。我在上面添加了一些 sql 可能会清楚地说明这一点
    • @frosty 好吧,这正是映射在说什么,这正是 NHibernate 的工作(如果你不使用 NHibernate 的默认值,你可能需要在 one-to-one 关系中添加一个 column 属性)。你试过了吗?
    • 谢谢,我找不到一对一的列属性。我已经设置了多对一,它似乎可以工作,除了我认为我现在已经发布了会话。我已经发布了一个关于此的新问题。
    • 我在另一篇文章中看到了类似的答案,这是我还没有完全理解的问题——这就是为什么 1-1 对象关系应该映射为 Nhib 的 M-1。您能否简要解释一下为什么这是有道理的,或者请我参考一个这样做的链接?此外,如果您可以编辑您的帖子以反映多对一映射。干杯
    猜你喜欢
    • 2011-06-14
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    相关资源
    最近更新 更多