2009-12-09 49 views
0

我在我的数据库中的这些相关的表:NHibernate的:如何正确模拟这种模式

 
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. 

这就是他们目前在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> 

我知道,这个映射呢不太适合附件表的模式。
有没有更好的方法来映射这些表?

(这与my previous question。)

+0

正如一个附注,而不是你的问题的实际答案,你的映射文件中的类型声明不需要显式声明“System.String”,你可以简单地放在“string”中。 – Jay 2009-12-09 01:27:12

+0

你甚至不需要在大多数情况下指定类型。 NHibernate默认会使用属性类型。有些情况下你想要,比如枚举或者自定义类型。 – 2009-12-09 01:45:55

+0

名称/列相同。 NHibernate使用约定,即列名与属性名称相同,除非另有指定。 – 2009-12-09 01:47:09

回答

2

要详细说明上述答案,可以使用多对一元素来设置关系并使用集合映射使关系成为双向关系,这似乎对您的模式可能有用。

您可以在附件映射中使用多对一的元素。例如,

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

而且你可以指定映射逆的文件:

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

你可以做同样的事情的文件。上面的名字只是来自模式,但你仍然需要确保它们与他们的类匹配等。但这是总体思路。