Nhibernate多对多桥表保持空

时间:2012-05-01 18:37:41

标签: c# nhibernate nhibernate-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>

项目类映射:

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

2 个答案:

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

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

答案 1 :(得分:0)

您需要将用户添加到Users中每个Projects的{​​{1}}属性中。

Save -

之前添加以下循环
foreach (Project project in u.Projects)
{
   project.Users.Add(u);
}