public async Task <FinancialProjectDto> Handle(CreateFinancialProjectCommand request, CancellationToken cancellationToken) { var entity = new FinancialProject { Id = Guid.NewGuid().ToString(), Title = request.Title, Description = request.Description }; var users = new List <FinancialProjectApplicationUser>(); foreach (var applicationUser in request.Users) { users.Add(new FinancialProjectApplicationUser { FinancialProjectId = entity.Id, UserId = applicationUser.Id }); await CreateOweRecord(request.Users, entity.Id, applicationUser.Id, cancellationToken); } entity.FinancialProjectApplicationUsers = users; await _context.FinancialProjects.AddAsync(entity, cancellationToken); await _context.SaveChangesAsync(cancellationToken); return(_mapper.Map <FinancialProjectDto>(entity)); }
private async Task AddNewUsers(UpdateFinancialProjectCommand request, FinancialProject entity, CancellationToken cancellationToken) { foreach (var newUser in request.Users.Where(newUser => entity.FinancialProjectApplicationUsers .All(x => x.UserId != newUser))) { var user = new FinancialProjectApplicationUser { FinancialProjectId = _financialProjectId, UserId = newUser }; await _context.FinancialProjectApplicationUsers.AddAsync(user, cancellationToken); } }
private async Task RemoveUsers(UpdateFinancialProjectCommand request, FinancialProject entity, IQueryable <OweRecord> oweRecords, CancellationToken cancellationToken) { foreach (var removedUser in entity.FinancialProjectApplicationUsers.Where(x => request.Users.All(y => y != x.UserId))) { _context.FinancialProjectApplicationUsers.Remove(removedUser); var recordFromRemovedUser = oweRecords.Where(x => x.UserId == removedUser.UserId); _context.OweRecords.RemoveRange(recordFromRemovedUser); var recordToRemovedUser = oweRecords.Where(x => x.OwedUserId == removedUser.UserId); _context.OweRecords.RemoveRange(recordToRemovedUser); } }