public async Task <IActionResult> Patch([FromBody] JsonPatchDocument <AppUser> patch) { //视频【65】 //有数组的情况下,更新有点复杂, //1先删除原先的在做新增操作 //2.匹配后,在做关联操作,(不要跟踪数据) var user = await _dbContext.AppUsers .SingleOrDefaultAsync(x => x.Id == UserIdentity.UserId); if (user == null) { throw new UserOperationException($"错误的用户上下文Id {UserIdentity.UserId}"); } patch.ApplyTo(user); foreach (var item in user?.Properties) { _dbContext.Entry(item).State = EntityState.Detached; } var currentPros = user.Properties; var originPros = await _dbContext.AppUserProperties.AsNoTracking().Where(x => x.AppUserId == user.Id).ToListAsync(); var allPros = originPros.Union(currentPros).Distinct(); var removeRang = originPros.Except(currentPros); _dbContext.RemoveRange(removeRang); var addRang = allPros.Except(originPros); using (var trans = await _dbContext.Database.BeginTransactionAsync()) { //发布用户变更的消息 await RasieUserInfoChangedEventAsyncTask(user); await _dbContext.AddRangeAsync(addRang); await _dbContext.SaveChangesAsync(); trans.Commit(); } return(Json(user)); }
public async Task CreateMany(List <T> entity) { if (entity != null) { await _context.AddRangeAsync(entity); try { await _context.SaveChangesAsync(); } catch (DbUpdateException ex) { _logger.LogError("Error saving data", ex); throw new Exception("Error saving data", ex); } catch (Exception e) { _logger.LogError(e.Message); throw; } } }