2012-05-01 78 views
2

我有兩個表與橋表有多對多的關係。Nhibernate多對多橋表保留爲空

用戶類別映射:

<class name="MatrixCore.User" table="MatrixUser" lazy="false"> 
    <id name="ID" column="ID" unsaved-value="0"> 
     <generator class="native"/> 
    </id> 
    <property name="FirstName"/> 
    <property name="LastName"/> 
    <property name="UserName"/> 
    <property name="Password"/> 
    <many-to-one name="UserType" class="MatrixCore.UserType" /> 
    <set name="Projects" table="UserInProject" cascade="All"> 
     <key column="MatrixUser_ID"/> 
     <many-to-many class="Project" column="Project_ID"/> 
    </set> 
    </class> 

項目類映射:

<class name="MatrixCore.Project" table="Project" lazy="false"> 
    <id name="ID" column="ID" unsaved-value="0"> 
    <generator class="native"/> 
    </id> 
    <property name="Name" /> 
    <property name="Acronym"/> 
    <property name="StartDate"/> 
    <property name="EndDate"/> 
    <set name="Users" table="UserInProject" cascade="All"> 
    <key column="Project_ID"/> 
    <many-to-many class="User" column="MatrixUser_ID" /> 
    </set> 
</class> 

的類的實現是過於簡單每個類有一個集合的其他的 。 我試圖在表中插入記錄橋表保持爲空。

ICollection<Project> ps = new HashSet<Project>() { project}; 

      UserType tp = (UserType)session.Get("UserType", 1); 
      User u = new User() 
      { 
       FirstName = "Hussein", 
       LastName = "Hussein", 
       UserName = "Hussein", 
       Password = "welcome", 
       UserType = tp, 
       Projects = ps 
      }; 

      session.Save(u); 
+0

你真的應該創建一個臨時表(ProjectUsers)引用項目和用戶預防nt多對多的關係:) – mattytommo

+0

有一張表重讀映射請求:) –

回答

2

試試這個映射 用戶類

<set name="Projects" table="UserInProject" inverse="true" cascade="save-update" lazy="false"> 
    <key column="MatrixUser_ID" /> 
    <many-to-many class="Project" column="Project_ID"/> 
</set> 

和項目

<set name="Users" table="UserInProject" cascade="save-update" lazy="false"> 
    <key column="Project_ID" /> 
    <many-to-many class="User" column="MatrixUser_ID"/> 
</set> 
+0

謝謝sleiman它的工作原理很好,你可以解釋反向屬性如何解決問題我有點愣住了。 –

+2

[這會有所幫助](http://stackoverflow.com/questions/713637/inverse-attribute-in-nhibernate) –

0

您需要將用戶添加到Users財產在Projects的每一個。

添加下面的循環之前Save -

foreach (Project project in u.Projects) 
{ 
    project.Users.Add(u); 
} 
+0

不,這不是問題 –