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:
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.
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.