Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8068625
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T12:45:10+00:00 2026-06-05T12:45:10+00:00

I have 2 tables with manyToMany relationship. user can have many groups and groups

  • 0

I have 2 tables with manyToMany relationship. user can have many groups and groups can have many users.

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; }
}

I use Fluent NHibernate to AutoMap them as follows:

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

As a result Nhibernate produce 3 tables:
1. Users – Mapped object table
2. Groups Mapped Object table
3. UserToGroup – generated association table

The requirement is to have the following functionality on these tables:
1. AddUser(UInt64 UserId, IEnumerable groups)
2. RemoveGroup(GroupGuid groupGuild)
3. Dictionary> GetGroupToUsers();

AddUser method is work Ok, All table updated OK:
* Insert of new user in User table. OK
* Insert of new group in Group table. OK
* Insert of new relations recods in UserToGroup 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);
}

I use the following code to Remove group:

public void RemoveGroup(GroupGuid groupGuild)
{
     IList<Group> groupsToRemove = Session.QueryOver<Group>().Where(
            row => row.GroupGuid == groupGuild).List();
     foreach (Group group in groupsToRemove)
     {
          group.Users.Clear();
          Session.Delete(group);
     }
}

RemoveGroup method failed with the following exception:

threw exception: 
NHibernate.Exceptions.GenericADOException: could not delete: [StorageObject.Group#11111111-1111-1111-1111-111111111111][SQL: DELETE FROM "Group" WHERE Id = ?] ---> System.Data.SqlServerCe.SqlCeException: The primary key value cannot be deleted because references to this key still exist. [ Foreign key constraint name = FK4B29424018FA0CD4 ]

I understand that Group table can’t be delete since the reference UserToGroup table point to Group table.

  1. 1st question: how can I make hibernate to understand that I want to be able to controller this manyToMany relation from both side:
    Add users with groups – from user side.
    And delete groups – from group side

I tried to move Inverse to the User table but in this case when I add a User the association table is not populate.

What is the best way to define this kind of manyToMany relation?

Update:
Another way I tried is to have List of Users also in Groups in this configuration removeGroup is wokring but addUser in not working for specific scenario:

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

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

Now I have a bidirectional many to many.
My Fluent mapping is:

.Override<User>(obj => obj.HasManyToMany(x => x.Groups).ParentKeyColumn("UserId").ChildKeyColumn("GroupId").Table("UserToGroup").Cascade.SaveUpdate()
.Override<Group>(obj => obj.HasManyToMany(x => x.Users).ParentKeyColumn("GroupId").ChildKeyColumn("UserId").Table("UserToGroup")

If I use this configuration RemoveGroup works fine but AddUser is not working for the following case:
When adding 2 Users which contains the same Group the association table delete the first relation and holds just the last reference instead of having both relations.
Please advise.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T12:45:11+00:00Added an answer on June 5, 2026 at 12:45 pm

    Try to add an inverse collection in Group:

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

    In your mapping:

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

    Your Remove method:

    public void RemoveGroup(GroupGuid groupGuild)
    {
         IList<Group> groupsToRemove = Session.QueryOver<Group>().Where(
                row => row.GroupGuid == groupGuild).List();
         foreach (Group group in groupsToRemove)
         {
              group.Users.Clear();   // Removes references from all users pointing to that group
              Session.Delete(group);
         }
    }
    

    When you commit the transaction, the references should be automatically removed. I never tried this by myself, but it might work for you.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have 2 tables with manyToMany relationship. public class User { public virtual Guid
i have two tables: Authority , Permission they have many to many relationship class
I have this 2 classes: @Entity public class Student extends User { ... @ManyToMany(mappedBy
I have two tables: Users and Roles. A user may have more roles, so
I have a many-to-many relationship between 2 tables that I define with a join
OK, I have mapped with annotations two tables with a bidirectional @ManyToMany relationship. Now
I have two tables/entities client and site that have a many to many relationship
I have a M:N relationship between table Users and Groups . Now I am
I have a Group table with ManyToMany relationship with the User table via a
I have defined a many-to-many relationship between my two entity classes User and Permission.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.