NHibernate使用鉴别器映射集合

时间:2010-02-09 22:46:55

标签: c# nhibernate mapping

假设我有一个名为Images的类/表,就像现在一样,它的绑定方式类似于:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Domain.Image, Domain" table="Images">
    <id name="id" column="ImageID" access="field" unsaved-value="0">
      <generator class="identity" />
    </id>    
<!-- other properties -->
    <property name="AssociatedObjectID" column="AssociatedObjectID" />
    <property name="AssociatedObjectType" column="AssociatedObjectType" />
  </class>
</hibernate-mapping>

到目前为止,这个模式已经起作用,因为图像只与一个对象相关联,所以我可以在没有鉴别器的情况下保留该参考。

但是,现在我希望在另一个名为PhotoShoot的实体上收集这些图像。每个PhotoShoot都可以有多张图片。

有没有办法绑定一个集合,这样我可以在List<Image>内有一个PhotoShoot而无需提取基类并使用每个层次的表继承模式?

如果没有,那么每个层次的表格真的是最好的方式吗?我讨厌创建子类,特别是因为没有什么需要从Image实体中抽象出来。

2 个答案:

答案 0 :(得分:1)

我会将其映射为IList&lt; Images&gt; PhotoShoot上的属性,通过连接表(多对多)映射。

如果列表的顺序很重要,则将其映射为列表,否则作为包。我已经包含了两个映射。

<class name="Domain.PhotoShoot, Domain" table="PhotoShoot">
    <id name="id" column="PhotoShootId" access="field" unsaved-value="0">
      <generator class="identity" />
    </id>    
    <!-- other properties -->

    <!-- unordered list -->
    <bag name="Images" table="PhotoShoot_Image" fetch="join" cascade="all-delete-orphan">
        <key column="PhotoShootId"/>
        <many-to-many class="Domain.Image, Domain" column="ImageId" />
    </bag>

    <!-- ordered list -->
    <list name="Images" table="PhotoShoot_Image" fetch="join" cascade="all-delete-orphan">
        <key column="PhotoShootId"/>
        <imdex column="position" />
        <many-to-many class="Domain.Image, Domain" column="ImageId" />
    </list>
</class>

public class PhotoShoot
{
    IList<Image> Images { get; set; }
}

使用@ddango的原始类映射我们可以改为执行以下操作。

<class name="Domain.PhotoShoot, Domain" table="PhotoShoot">
    <bag name="Images" table="Image" fetch="join" where="AssociatedObjectType='PhotoShoot'">
        <key column="AssociatedObjectId"/>
        <one-to-many class="Domain.Image, Domain" />
    </bag>
</class>

答案 1 :(得分:0)

您可以使用多对多映射表,而不是将AssociatedObjectId / Type放在图像类/表中。在Hibernate中使用很多东西有点麻烦,但是给你一些额外的灵活性。

Image
-----
Id (PK)
OtherProp1
OtherProp2

Attachment
----------
Id (PK)
OtherProp1

AttachmentImage (many-to-many between Attachment and Images)
---------------
ImageId (PK, FK to Image.Id)
AttachmentId (PK, FK to Image.Id)

PhotoShoot
----------
Id (PK)
OtherProp1
-- AttachmentId (if PhotoShoot has only a single attachment)

PhotoShootAttachment (if Photoshoot can have many attachments)
--------------------
ImageId (PK, FK to Image.Id)
AttachmentId (PK, FK to Attachment.Id)
相关问题