0

我在用户和角色之间有一个多对多的关系。它们的设置如下:

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

在我添加新用户的代码中,我希望能够向该用户添加角色。但每当我这样做时,新角色也会添加到角色表中。这样做的正确方法是什么?

[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();
            } }
4

1 回答 1

0
entity.Roles.Add(new Role { RoleId = i, RoleName = role.RoleName });

这是问题所在,因为您创建了新实例,这意味着绝对是新角色。您必须从您的上下文中使用角色:

foreach (int i in user.Roles)
            {
                Role role = _repository.GetRoleByRoleId(i);
                entity.Roles.Add(role); // don't create new instance here!
            }
于 2013-01-01T11:41:09.133 回答