2009-07-10 56 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,并且在数据库中您可以在应用程序和申请人之间具有多对一关系可以有多个申请与申请人相关联。