Haimon
Haimon

Reputation: 227

NHibernate: Implementing ManyToMany Relationship

I have 2 tables with manyToMany relationship.

public class User
{
   public virtual Guid Id { get; set; }
   public virtual UInt64 UserId { get; set; }
   public virtual IList<Group> Groups{ get; set; }
}

public class Group
{
   public virtual Guid Id { get; set; }
   public virtual Guid GroupGuid  { get; set; }
   public virtual IList<User> Users{ get; set; }
}

I use Fluent NHibernate to AutoMap them as follows:

.Override<User>(obj => obj.HasManyToMany(x => x.Groups).Table("UserToGroup").Cascade.AllDeleteOrphan())

.Override<Group>(obj => obj.HasManyToMany(x => x.Users).Table("UserToGroup").Cascade.AllDeleteOrphan().Inverse())

When I add a User which contains groups list, All table updated OK: Insert of new user in User table. OK Insert of new group in Group table. OK Insert of new relation inUserToGroup table. OK

I use the following code to add a User (including groups):

public void AddUser(User userData, IList<Guid> groupIds)
{
   User user = new User();
   user.UserId = userData.UserId;

   IList<User> Users = new List<Users();
   Users.Add(user);

   IList<Group> groups = new List<Group>();

   foreach (Guid groupId in groupIds)
   {
      Group grp = new Group();
      grp.GroupGuid = groupId;
      grp.Users = Users;
      groups.Add(grp);
   }

   user.Groups = groups;
   Session.Save(user);
}

The problem: When I add a new User that contains a GroupGuid that is already exist in Group table, a new record is inserted to Group table with the same GroupGuid and new id.

Questions:

  1. How do I make NHibernate adding only new GroupGuid ids to Group table ? and still add a relation in UserToGroup table which related the new User to the exist Group.

  2. In AddUser method - should I set both side with entity i.e. set user.Groups with group list and set group.Users with user list ?

Thanks, Haimon.

Upvotes: 3

Views: 204

Answers (1)

Vadim
Vadim

Reputation: 17957

The reason you are experiencing this is because you are likely using unassociated Group entities when you associate them with your User object. So you need to load them from the database.

Alternatively, you can switch to using the Guids as the id for the entity, instead of whatever other primary key you've set up.

To answer your second question, you should just be able to set one side of the relationship. However, I'm confused as to why you would have 2 separate tables for the relationship. You typically only need 1 other table:

User
Group
UserGroup

Upvotes: 2

Related Questions