zoukankan      html  css  js  c++  java
  • 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();
            }
  • 相关阅读:
    ABAP接口用法
    监听textarea数值变化
    The first step in solving any problem is recognizing there is one.
    Wrinkles should merely indicate where smiles have been.
    God made relatives.Thank God we can choose our friends.
    Home is where your heart is
    ABAP跳转屏幕
    Python 工具包 werkzeug 初探
    atom通过remote ftp同步本地文件到远程主机的方法
    Mongodb学习笔记一
  • 原文地址:https://www.cnblogs.com/ldybyz/p/6215194.html
Copyright © 2011-2022 走看看