2

I have two tables with a many-to-many relation with a bridge table.

User Class Mapping :

<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>

Project class mapping :

<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>

the classes implementations are too simple each class have a collection of the other. I am trying to insert records in the tables the bridge table keep to be empty.

    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);
Gerard
  • 2,461
  • 2
  • 26
  • 34
Hussein Zawawi
  • 2,907
  • 2
  • 26
  • 44

2 Answers2

2

try this mapping for user class

<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>

and for Project Class

<set name="Users" table="UserInProject" cascade="save-update" lazy="false">
  <key column="Project_ID"  />
  <many-to-many class="User" column="MatrixUser_ID"/>
</set>
Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
0

You need to add the user to the Users property in each one of the Projects.

Add the following loop before the Save -

foreach (Project project in u.Projects)
{
   project.Users.Add(u);
}
Mr Mush
  • 1,538
  • 3
  • 25
  • 38