0
votes

I am trying to setup a many-to-many mappings using NHibernate 4 and Fluent Nhibernate 2. It is a simple User and Role relationship. One user may have many roles and one role may have many users. Below is the structure.

User

public User()
{
    Id = Guid.NewGuid();
    Roles = new List<Role>();
}

public virtual Guid Id { get; set; }        
public virtual string Name { get; set; }
public virtual IList<Role> Roles { get; set; }

Role

public Role()
{
    Id = Guid.NewGuid();
    Users = new List<User>();
}

public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<User> Users { get; set; }

UserMap

Id(x => x.Id).Column("Id").GeneratedBy.Assigned();
Map(x => x.Name);
HasManyToMany(x => x.Roles)
    .Cascade.AllDeleteOrphan()
    .Inverse()
    .Table("UserRole")
    .ParentKeyColumn("ObjUser")
    .ChildKeyColumn("ObjRole");

RoleMap

Id(x => x.Id).Column("Id").GeneratedBy.Assigned();
Map(x => x.Name);
HasManyToMany(x => x.Users)
    .Cascade.None()
    .Table("UserRole")
    .ParentKeyColumn("ObjRole")
    .ChildKeyColumn("ObjUser");

Updating existing user

User objUser = UserManager.Get(_userId);
objUser.Name = txtName.Text;
foreach (ListItem itemRole in chksRoles.Items)
{
     if (itemRole.Selected)
     {
           objUser.Roles.Add(RoleManager.Get(new Guid(itemRole.Value)));
     }
}

I have a UserRole table for the associations and it only consists ObjRole and ObjUser column. The problem I have below.

1) I am able to insert a new record when I am creating a new user and set multiple roles to it. But when I am trying to update an existing user by changing it's roles, it does not update the associations in fact, nothing is happened. The roles being to the user are still the same.

2) How do I set the cascade if I would not want to create a new user when I am creating a new role? The reason being when I am creating a new role, there will be no user that will be in this role.

I am trying to figure out this using the hasmanytomany mappings as I do not store any other fields in the UserRole table so I don't think it is necessary to handle it using 2 one-to-many mappings in both User and Role table.

Appreciate if anyone is able to help on this :) Have been working on this since yesterday night. Thank you very much.

1

1 Answers

0
votes

It is an issue related to inverse setting. And solution is really easy - follow the good practice.

In this case, set both sides of relationship - always:

var role = RoleManager.Get(new Guid(itemRole.Value));
objUser.Roles.Add(role);
role.Users.Add(objUser);