2009-07-10 54 views
1

我是新來NHibernate和我使用NHibernate 2.1.0 RC1。在C#中,我有以下類別:需要幫助NHibernate的映射(父/子關係)

public class Application 
{ 
    public virtual int Id { get; set; } 
    public virtual Applicant Applicant { get; set; } 
} 

public class Applicant 
{ 
    public virtual int Id { get; set; } 
    public virtual string FirstName { get; set; } 
    public virtual string LastName { get; set; } 
    public virtual IList<Application> Applications { get; set; } //maybe i should use set to eliminate duplicates 
} 

而且我在SQL Server 2005中的下列數據庫模式:

Applications table 
{ 
    ApplicationId int PK IDENTITY NOTNULL 
    FK_ApplicantId int FK NOTNULL 
} 

Applicants table 
{ 
    ApplicantId int PK IDENTITY NOTNULL 
    FirstName string NOTNULL 
    LastName string NOTNULL 
} 

而且我有以下NHibernate的映射文件:

我需要雙向映射:

  • 1申請人可以有> 1級的應用
  • 1申請屬於1名申請人

我不知道如何應用集合映射到申請人。請幫忙。謝謝! 另外我不使用Fluent Nhibernate,因爲它似乎不支持Nhibernate 2.1.0 RC1。

更新(這是工作版本):

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

    <class name="Application" table="Applications"> 
    <id name="Id" column="ApplicationID" /> 
    <property name="Reference" /> 

    <many-to-one name="Applicant" column="ApplicantID" not-null="true"/> 
    </class> 

    <class name="Applicant" table="Applicants"> 
    <id name="Id" column="ApplicantID" /> 
    <property name="FirstName" column="FirstName" /> 
    <property name="LastName" column="LastName" /> 

    <set name="Applications" inverse="true"> <!-- good to remove this mapping --> 
     <key column="ApplicantID"/> 
     <one-to-many class="Application"/> 
    </set> 
    </class> 
</hibernate-mapping> 

我也將消除從申請對象的應用程序集合,以減少負載成千上萬的應用程序,申請人提交的變化。 Reason for this is here.

+0

見https://www.hibernate.org/hib_docs/nhibernate/html/example-parentchild.html – 2009-07-10 04:01:57

+0

我讀它謝謝。完成後我會發布更新後的映射文件。 – Jeff 2009-07-10 04:12:22

回答

1
<?xml version="1.0" encoding="utf-8" ?> 
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" 
        assembly="HelloWorld" 
        namespace="HelloWorld"> 

    <class name="Application" table="Applications"> 
    <id name="Id" column="ApplicationID" /> 
    <property name="Reference" /> 

    <many-to-one name="Applicant" column="ApplicantID" not-null="true"/> 
    </class> 

    <class name="Applicant" table="Applicants"> 
    <id name="Id" column="ApplicantID" /> 
    <property name="FirstName" column="FirstName" /> 
    <property name="LastName" column="LastName" /> 

    <set name="Applications" inverse="true"> 
     <key column="ApplicantID"/> 
     <one-to-many class="Application"/> 
    </set> 
    </class> 
</hibernate-mapping> 
1

也有一些是不對您的層次結構。爲什麼申請人有一系列申請,其中每個申請都被分配給另一個申請人?請重新檢查您的對象以及您正在嘗試構建的關係。您可以只擁有一個應用程序類和一個申請人類,並且一個應用程序可以擁有多個應用程序,只需要在應用程序類中擁有申請人ID,並且在數據庫中您可以在應用程序和申請人之間具有多對一關係可以有多個申請與申請人相關聯。