public async Task <IActionResult> AddTodoItemTag(string todoItemId, [FromBody] TodoItemTagAddRequest tag) { TodoItemTagDto res = null; TodoItemTag model = null; try { if (string.IsNullOrEmpty(tag.TagName)) { model = await _dataProvider.AddTag(todoItemId, tag.TagId); } else { model = await _dataProvider.AddTag(todoItemId, tag.TagName); } } catch (Exception ex) { Console.WriteLine(ex); throw; } res = _mapper.Map <TodoItemTagDto>(model); var resObj = new ObjectResult(res); return(resObj); }
private async Task UpdateTodoTags(TodoItem item, IEnumerable <string> tags) { var existingTags = await _context.Tags .Where(t => tags.Any(s => s == t)) .ToDictionaryAsync(t => t.Name); var existingMappings = item.TagsMapping?.ToDictionary(m => m.Tag.Name) ?? new Dictionary <string, TodoItemTag>(); item.TagsMapping = tags .Select(t => { TodoItemTag result; if (existingMappings.TryGetValue(t, out result)) { return(result); } result = new TodoItemTag { TodoItem = item }; if (existingTags.TryGetValue(t, out Tag tag)) { result.Tag = tag; } else { result.Tag = new Tag { Name = t }; } return(result); }) .ToList(); foreach (var mapping in existingMappings) { if (item.TagsMapping.All(x => x != mapping.Value)) { _context.Remove(mapping.Value); } } }