views:

60

answers:

2

I have these related tables in my database:

table [Files]:
FileID    FileName
------    --------
1         /data/foo.jpeg
2         /data/bar.gif

table [Attachments]:
FileID    DocumentID    Caption
------    ----------    -------
1         10            Foo is awesome.
1         20            Foo is horrible.
2         10            Bars are my favorite.

table [Documents]:
DocumentID    Title
----------    -----
10            Things Jack loves.
20            Stuff Mary hates.

This is how they are currently mapped in NHibernate:

<class name="File" table="Files">
    <id name="Id" type="System.Int32" column="FileID">
        <generator class="identity" />
    </id>
    <property name="FileName" column="FileName" type="System.String" />  
</class>

<joined-subclass name="Attachment" table="Attachments" extends="File">
    <key column="FileID" />
    <property name="DocumentID" column="DocumentID" type="System.Int32" />
    <property name="Caption" column="Caption" type="System.String" />
</joined-subclass>

<class name="Document" table="Documents">
    <id name="Id" type="System.Int32" column="DocumentID">
        <generator class="identity" />
    </id>
    <property name="Title" column="Title" type="System.String" />
</class>

I know that this mapping does not quite fit the schema for the Attachments table.
Is there a better way to map these tables?

(This is related to my previous question.)

A: 

You are asking how to enforce relationship between Attachment and Document? If true just refer to "many-to-one" element.

Mike Chaliy
+2  A: 

To elaborate on the above answer, you can use the many-to-one element to set up the relationship and use collection mapping to make the relationship bi-directional, which seems like it could be useful to your schema.

You'd use the many-to-one element in the mapping for the attachments. For example,

<many-to-one name="File" class="File" column="FileID"/>

And you can specify the inverse on the mapping for files:

<set name="Attachments" inverse="true" lazy="true">
    <key column="FileID" />
    <one-to-many class="Attachment" />
</set>

You can do the same thing for the documents. Names above are just taken from the schema, but you'd still need to make sure they match their classes and etc. But that's the overall idea.

jrcalzada