R – NHibernate Many To Many Relationship – Issue when deleting a part of the relationship


I have a many to many relationship between a Team and an Employee entity.

I mapped them as following:

public class EmployeeMap : ClassMap<Employee>
    public EmployeeMap()
        // identifier mapping
        Id(p => p.Id).Column("EmployeeID");

        // column mapping
        Map(p => p.EMail);
        Map(p => p.LastName);
        Map(p => p.FirstName);

        // relationship mapping
        HasManyToMany(m => m.Teams).Table("EmployeeTeam")

        HasMany(p => p.LoanedItems).Cascade.SaveUpdate().KeyColumn("EmployeeId");

public class TeamMap : ClassMap<Team>
    public TeamMap()
        // identity mapping
        Id(p => p.Id).Column("TeamID");

        // column mapping
        Map(p => p.Name);

        // relationship mapping
        HasManyToMany(m => m.Employees)

Then I created 3 Teams and 2 Employees:

TeamID  EmployeeID
1       1
1       2
2       2
3       1

The Employee1 has also 2 LoanedItems(Books, Magazines). Employee2 has no LoanedItems.

Now I want to delete Employee1, who is in Team1 and Team3. In Team 1 is also Employee2.
So when I delete Employee1, I assume that Employee1 is deleted and also Team3, because I also assume that an Team can only exist when it has an Employe and vice versa. So Team1 may not be deleted, because it has Employee2 and can still exists.

I used the following code lines with a new Session:

var loadedEmployee = session.Get<Employee>(1);

But what happens?
-> NHibernate deletes all Teams and all Employees!
-> NHibernate updated my LoanedItem table correctly by setting the FK EmployeeID to NULL.

What is wrong there?

Best Solution

I have answered a similar question here: What is the correct way to define many-to-many relationships in NHibernate to allow deletes but avoiding duplicate records

Reading the question and my answer maybe will help you understand what is going on with your many-to-many association.

Related Question