Search code examples
nhibernatemany-to-manybidirectional-relation

NHibernate Many to Many table is not updated


I have a 3 tables which are "News", "Tags", "News_Tags" with Many-To-Many relationship.

With the following mapping the "News" and "Tags" table have been updating, but "News_Tags" has not been updated.

Can anyone help me?

News:

<class name="News" table="News" lazy="false">
  <id name="NewsID">
    <generator class="identity" />
  </id>
  <property name="Title"/>
  <set 
    name="TagsList" 
    table="News_Tags" 
    inverse="true" 
    lazy="false" 
    cascade="save-update">

      <key column="NewsID" not-null="true" />
      <many-to-many class="Tag" column="TagID" />
  </set> 
</class>

Tags:

<class name="Tag" table="Tags" lazy="false">
  <id name="TagID">
    <generator class="identity" />
  </id>
  <property name="TagName"/>
  <property name="DateCreated"/>

  <set 
    name="NewsList"
    table="News_Tags"
    inverse="true"
    lazy="false"
    cascade="save-update">

      <key column="TagID" not-null="true" />
      <many-to-many class="News" column="NewsID" />
  </set>

</class>

News_Tags

<class name="NewsTags" table="News_Tags" lazy="false">
  <id name="NewsTagID">
    <generator class="identity" />
  </id>    
  <property name="TagID"/>
  <property name="NewsID"/>
</class>

many thanks

Daoming.


Solution

  • There are some strange things in this mapping.

    • Both collections, TagsList and NewsList, are inverse. So NHibernate does not store them. Inverse means: "this information is already in another collection, so ignore this when storing". Put inverse on only one side of the bidirectional relation.
    • NewsTags is mapped as a class, even if it is not a class. It is just a table in the database, used to map a (bidirectional) many-to-many relation. Just remove this class mapping.
    • the cascade is set by both collections. I'm not sure if you want to create new tags if they are referenced by a News instance, but you most probably never want to create new News instances because they are referenced by some tag. I would remove it there.