EF多对多更新报错(TableNoTracking引发的bug)

实体映射关系如下,SISTUser和SISTUserRoles存在多对多的关系,生成中间表

 public partial class SISTUserMap: EntityTypeConfiguration<SISTUser>
    {
        public SISTUserMap()
        {
            this.ToTable("SISTUser");
            this.HasKey(u => u.Id);
            this.Property(u => u.Id).HasColumnName("UserId");

            this.Property(u => u.UserName).HasMaxLength(100);
            this.Property(u => u.Email).HasMaxLength(100);

            this.HasMany(u => u.SISTUserRoles)
                .WithMany()
                .Map(m => m.ToTable("SISTUser_SISTUserRole_Mapping"));

        }
    
    }

 

更新操作

public ActionResult SetUserRole(string UserId, string RoleId)
        {
            try
            {
                SISTUser user = _userService.GetUserByUserId(UserId);
                var allUserRoles = _userService.GetSISTRoles();
                foreach (var userRole in allUserRoles)
                {
                   if(userRole.Id==RoleId)
                   {
                       if (user.SISTUserRoles.Count(cr => cr.Id == userRole.Id) == 0)
                           user.SISTUserRoles.Add(userRole);
                   }

                    else
                   {
                       if (user.SISTUserRoles.Count(cr => cr.Id == userRole.Id) > 0)
                           user.SISTUserRoles.Remove(userRole);
                   }
                }

                _userService.UpdateUser(user);

                return Json(new BaseJsonResult<object> { success = true, msg = "编辑成功", data = null });
            }

            catch (Exception ex)
            {
                return Json(new BaseJsonResult<object> { success = false, msg = ex.Message, data = null });
            }
        }

 

结果报错:违反了 PRIMARY KEY 约束 'PK_dbo.SISTUserRole'。

 

原因是下面的查询使用了TableNoTracking,具体底层原理待考察

  public virtual IList<SISTUserRole> GetSISTRoles()
        {
            //使用TableNoTracking会报错
            return _sISTUserRoleRepository.Table.ToList();
        }

 

posted @ 2016-12-23 16:18  ldybyz  阅读(1281)  评论(0编辑  收藏  举报