public async Task <IActionResult> PutPost([FromRoute] int id, [FromBody] EditPostProxy editPostProxy) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != editPostProxy.Id) { return(BadRequest()); } var post = new Post() { Id = editPostProxy.Id, Title = editPostProxy.Title, PostText = editPostProxy.Text, CategoryId = editPostProxy.CategoryId }; try { // Обновляем пост _context.Entry(post).State = EntityState.Modified; await _context.SaveChangesAsync(); // Удаляем старые теги поста _context.PostTags.RemoveRange(_context.PostTags.Where(pt => pt.PostId == post.Id)); await _context.SaveChangesAsync(); // Добавляем новые теги поста foreach (var tag in editPostProxy.Tags) { _context.PostTags.Add(new PostTags() { PostId = post.Id, TagId = tag.Id }); } await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException e) { if (!PostExists(id)) { return(NotFound()); } else { throw; } } catch (Exception e) { return(BadRequest()); } return(NoContent()); }
public async Task <IActionResult> PostPost([FromBody] EditPostProxy editPostProxy) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var post = new Post() { Title = editPostProxy.Title, PostText = editPostProxy.Text, CategoryId = editPostProxy.CategoryId, PublishTime = DateTime.Now, Image = "500x350.png" }; try { _context.Posts.Add(post); await _context.SaveChangesAsync(); foreach (var tag in editPostProxy.Tags) { _context.PostTags.Add(new PostTags() { PostId = post.Id, TagId = tag.Id }); } await _context.SaveChangesAsync(); } catch (Exception e) { return(BadRequest()); } return(Ok(new { id = post.Id })); }