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")
.Inverse()
.Cascade.All()
.AsSet()
.LazyLoad()
.ParentKeyColumn("EmployeeID")
.ChildKeyColumn("TeamID");
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)
.Table("EmployeeTeam")
.LazyLoad()
.Cascade.All()
.AsSet()
.ParentKeyColumn("TeamID")
.ChildKeyColumn("EmployeeID");
}
}
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);
session.Delete(loadedEmployee);
transaction.Commit();
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?