Created
January 12, 2023 14:48
-
-
Save nikitalarionov/b276b047938349e5940e39e8201eaf31 to your computer and use it in GitHub Desktop.
Example Post Controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Mvc; | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using MySite.Models; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.EntityFrameworkCore; | |
namespace MySite.Controllers | |
{ | |
[ApiController] | |
[Route("[controller]")] | |
public class PostController : ControllerBase | |
{ | |
private readonly MyAppContext _dbContext; | |
public PostController(MyAppContext context) | |
{ | |
_dbContext = context; | |
} | |
[HttpGet] | |
public IEnumerable<Post> Get() | |
{ | |
// Чтобы вернуть связанные сущности | |
// Надо обязательно добавить к обращению в контекст вызов Include | |
var posts = _dbContext.posts.Include((p) => p.Category) | |
.Include((p) => p.Tags); | |
return posts; | |
} | |
[HttpGet("{id}")] | |
public async Task<ActionResult<Post>> GetItem(long Id) | |
{ | |
var post = await _dbContext.posts.FindAsync(Id); | |
if (post == null) | |
{ | |
return NotFound(); | |
} | |
return post; | |
} | |
[HttpPost] | |
[ProducesResponseType(StatusCodes.Status201Created)] | |
[ProducesResponseType(StatusCodes.Status400BadRequest)] | |
public async Task<ActionResult<Post>> Add(Post post) | |
{ | |
_dbContext.Add(post); | |
await _dbContext.SaveChangesAsync(); | |
return CreatedAtAction(nameof(GetItem), new { id = post.Id }, post); | |
} | |
[HttpPut] | |
[ProducesResponseType(StatusCodes.Status200OK)] | |
[ProducesResponseType(StatusCodes.Status400BadRequest)] | |
public async Task<ActionResult<Post>> Edit(Post post) | |
{ | |
// 0 будет не валиден? | |
if (post.Id == null) | |
{ | |
return BadRequest(); | |
} | |
// Пока без этого вроде работает нормально | |
// Untrack previous entity version | |
// var trackedEntity = _dbContext.Set<Post>().SingleOrDefaultAsync(e => e.Id == post.Id); | |
// _dbContext.Entry<Post>(await trackedEntity).State = EntityState.Detached; | |
var postToUpdate = await _dbContext.posts | |
// TODO Read about no tracking | |
.AsNoTracking<Post>() | |
.Include(p => p.MainImage) | |
.Include(p => p.Category) | |
.Include(p => p.Tags) | |
.FirstOrDefaultAsync(p => p.Id == post.Id); | |
if (postToUpdate == null) | |
{ | |
return NotFound(); | |
} | |
// Помечаем что изменился этот пост | |
_dbContext.Entry(postToUpdate).State = EntityState.Modified; | |
// update fields on post from json request record | |
_dbContext.Entry(postToUpdate).CurrentValues.SetValues(post); | |
// remove or update child collection items | |
var tags = postToUpdate.Tags.ToList(); | |
foreach(var tag in tags) | |
{ | |
var newTag = post.Tags.SingleOrDefault(t => t.TagId == tag.TagId); | |
if (newTag != null) | |
{ | |
_dbContext.Entry(tag).CurrentValues.SetValues(newTag); | |
} else | |
{ | |
_dbContext.Remove(tag); | |
} | |
} | |
// Add new items | |
foreach (var tag in post.Tags) | |
{ | |
if (tags.All(i => i.TagId != tag.TagId)) | |
{ | |
postToUpdate.Tags.Add(tag); | |
} | |
} | |
// Вручную обновить связанную фотографию | |
// Вручную обновить связанную категорию | |
// Сохраняем изменения | |
await _dbContext.SaveChangesAsync(); | |
return postToUpdate; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment