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

  • Home
  • SEARCH
  • 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 9063639
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T16:03:17+00:00 2026-06-16T16:03:17+00:00

I have a Many to Many relationship between User and Role. They are set

  • 0

I have a Many to Many relationship between User and Role. They are set up as follows :

    public partial class User
    {
        //public User()
        //{
        //    //this.DateCreated = DateTime.Now; //set default value
        //    Roles = new HashSet<Role>();
        //}

        public ICollection<Role> Roles { get; set; } //many to many relationship

        public int UserId { get; set; }
        public string FirstName { get; set; }
        public string Surname { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public string City { get; set; }

        //foreign key
        public int CountryId { get; set; }
        //navigation properties
        public virtual Country Country { get; set; }

        //foreign key
        public int LanguageId { get; set; }
        //navigation properties
        public virtual Language Language { get; set; }

        public string EmailAddress { get; set; }
        public long? FacebookId { get; set; }
        public DateTime DateCreated { get; set; }
    }

public partial class Role
    {
        //public Role()
        //{
        //    Users = new HashSet<User>();
        //}

        public ICollection<User> Users { get; set; } //many to many relationship

        public int RoleId { get; set; }
        public string RoleName { get; set; }
    }

//many to many relationship 
            modelBuilder.Entity<User>().
              HasMany(c => c.Roles).
              WithMany(p => p.Users).
              Map(
               m =>
               {
                   m.MapLeftKey("UserId");
                   m.MapRightKey("RoleId");
                   m.ToTable("UserRoles", schemaName: "Main");
               });

In my code where I add a new user, I want to be able to add Roles to that user. But whenever I do this, new Roles are also added to the Roles table. What is the correct way to do this?

[HttpPost]
        public ActionResult UserAdd(UserDTO user)
        {
            if (ModelState.IsValid)
            {
                //do mapping manually here
                Country country = _repository.GetCountryByCountryId(user.CountryId);
                Language language = _repository.GetLanguageByLanguageId(user.LanguageId);

                User entity = new User();
                entity.FirstName = user.FirstName;
                entity.Surname = user.Surname;
                entity.Username = user.Username;
                entity.Password = user.Password;
                entity.City = user.City;
                entity.CountryId = country.CountryId;
                entity.LanguageId = language.LanguageId;
                entity.Country = country;
                entity.Language = language;
                entity.EmailAddress = user.EmailAddress;
                entity.FacebookId = null;
                entity.DateCreated = DateTime.Now;
                entity.Roles = new List<Role>();

                foreach (int i in user.Roles)
                {
                    Role role = _repository.GetRoleByRoleId(i);
                    entity.Roles.Add(new Role { RoleId = i, RoleName = role.RoleName });
                }

                int newUserId = _repository.AddUser(entity);

                return View();
            } }
  • 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-16T16:03:18+00:00Added an answer on June 16, 2026 at 4:03 pm
    entity.Roles.Add(new Role { RoleId = i, RoleName = role.RoleName });
    

    Here is the problem, because you create new instance, it means absolutely new role. You have to work with role from your context:

    foreach (int i in user.Roles)
                {
                    Role role = _repository.GetRoleByRoleId(i);
                    entity.Roles.Add(role); // don't create new instance here!
                }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a simple many-to-many relationship between the User class and the Place class.
I have a many-to-many relationship between User s and Task s. I want the
I have a one-to-many relationship between two classes for this situation. I have a
I have two domain classes with a many-2-many relationship between them, e.g. User and
Let's say I have a many-to-many relationship between users and group. A user can
Let's say you have a one-to-many relationship between Users and Orders (where one user
Here is the deal I have a one to many relationship between User and
I have many-to-many relationship between Game and Account models like below: class Account <
I have the following objects: public class User { int Id { get; set;
I have a many-to-many relationship between two models, Lists and Users. When a user

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.