We're using NHibernate for our membership system. A User
can be a member of many Role
s and a Role
can have many users.
When a Role
or a User
is deleted, it should only cascade the delete of the association record ("RoleUsers" table).
Deleting a Role
works as expected. However, deleting a User
does not delete the association record and as such fails due to a foreign key constraint.
My mapping on the Role
side:
HasManyToMany(r => r.Users)
.Access.CamelCaseField()
.Table("RoleUsers")
.ParentKeyColumn("RoleId")
.ChildKeyColumn("UserId")
.AsSet();
Mapping on the User
side:
HasManyToMany(u => u.Roles)
.Access.CamelCaseField()
.Table("RoleUsers")
.ParentKeyColumn("UserId")
.ChildKeyColumn("RoleId")
.Inverse(); // we'll add user to role, not role to user
And the failing test:
[Test]
public void Deleting_user_should_not_delete_roles()
{
var user = new User("john@doe.com", "John", "Doe", "Secr3t");
var role = new Role("Admin");
role.AddUser(user);
object id;
using (var txn = Session.BeginTransaction())
{
id = Session.Save(user);
Session.Save(role);
txn.Commit();
}
Session.Clear();
var fromDb = Session.Get<User>(id);
using (var txn = Session.BeginTransaction())
{
Session.Delete(fromDb);
txn.Commit();
}
Session.Query<Role>().Count().ShouldEqual(1);
}
I've tried every combination of Cascade
on the user mapping and it either fails or deletes the association record AND the role (not what I want).