【问题标题】:NHibernate many-to-many - how to retrieve property from join table and associate it with a child?NHibernate 多对多 - 如何从连接表中检索属性并将其与子关联?
【发布时间】:2010-10-26 23:00:07
【问题描述】:

我在 SQL 中有一个现有的多对多关系,它通过 NHibernate 映射到我的业务实体。

我想给子项(下面的类别)添加一个仅适用于父子关系的属性。在 SQL 中,我会在连接表中添加一个字段。

如何使用 NHibernate 从连接表中提取该值并将其与子属性关联?

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
  namespace="MyProject.Core.Entities"
  assembly="MyProject.Core">

  <class name="Product" table="Products" lazy="false">

    <id name="ProductId" access="field">
      <generator class="native" />
    </id>

    <property name="ProductName" access="field" />

    <idbag name="Categories" table="ProductCategory">
      <collection-id column="ProductCategoryId" type="int">
        <generator class="native" />                
      </collection-id>
      <key column="ProductId" />
      <many-to-many column="CategoryId" class="Category" />
    </idbag>

  </class>
</hibernate-mapping>

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
  namespace="MyProject.Core.Entities"
  assembly="MyProject.Core">

  <class name="Category" table="Categories" lazy="false">

    <id name="CategoryId" access="field">
      <generator class="native" />
    </id>

    <property name="CategoryName" access="field" />

  </class>
</hibernate-mapping>

【问题讨论】:

    标签: nhibernate nhibernate-mapping


    【解决方案1】:

    基本答案是您必须声明您的连接表并为其创建一个类。可以在这里找到类似的问题:

    How to use NHibernate ManyToMany with properties (columns) on Join Table (Fluent NHibernate)

    基于 cmets 的说明:

    Product one-to-many ProductCategory
    Category one-to-many ProductCategory
    ProductCategory many-to-one Product
    ProductCategory many-to-one Category
    

    【讨论】:

    • 所以我开始看到一种趋势。可以肯定地说,通过向我的多对多关系添加数据,我现在从父关系到关系是一对多,从关系到子关系是多对一?该关系是stackoverflow.com/questions/2713329/… 中建议的新实体吗?
    • 关系是一个新实体。 NHibernate 中的多对多本质上是一种快捷方式,当您没有在链接中包含任何额外数据时,它允许您跳过该步骤。您对关系的理解是正确的(我已将它们添加到答案中)。
    • 嗯,这需要一些努力,但现在可以了。我感谢松耦合和单元测试。感谢您朝着正确的方向推动。
    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多