112 lines
3.4 KiB
C#
112 lines
3.4 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using RDBMS_lab4.Models;
|
|
using RDBMS_lab4.ViewModels;
|
|
|
|
namespace RDBMS_lab4.Controllers
|
|
{
|
|
[Route("api/[controller]")]
|
|
public class PostsController : Controller
|
|
{
|
|
public PostsController()
|
|
{
|
|
}
|
|
|
|
[HttpGet("get")]
|
|
public IActionResult get()
|
|
{
|
|
try
|
|
{
|
|
using var context = new beautySalonContext();
|
|
var res = context.Posts.Include(p => p.Services).Select(p => new PostViue(p)).ToList();
|
|
return Ok(res);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return BadRequest(ex.Message);
|
|
}
|
|
}
|
|
[HttpGet("get/{Id}")]
|
|
public IActionResult get([FromRoute] int Id)
|
|
{
|
|
try
|
|
{
|
|
using var context = new beautySalonContext();
|
|
var res = context.Posts.Include(p => p.Services).FirstOrDefault(p => p.Id == Id);
|
|
if (res == null)
|
|
{
|
|
return Ok(null);
|
|
}
|
|
return Ok(new PostViue(res));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return BadRequest(ex.Message);
|
|
}
|
|
}
|
|
[HttpPost("create")]
|
|
public IActionResult create([FromBody] PostViue post)
|
|
{
|
|
try
|
|
{
|
|
using var context = new beautySalonContext();
|
|
var res = context.Posts.Add(new()
|
|
{
|
|
Name = post.Name,
|
|
Services = context.Services.Where(s => post.Services.Contains(s.Id)).ToList()
|
|
});
|
|
context.SaveChanges();
|
|
if (res == null)
|
|
{
|
|
return BadRequest(new NullReferenceException());
|
|
}
|
|
return Ok(new PostViue(res.Entity));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return BadRequest(ex.Message);
|
|
}
|
|
}
|
|
[HttpPut("update")]
|
|
public IActionResult update([FromBody] PostViue post)
|
|
{
|
|
try
|
|
{
|
|
using var context = new beautySalonContext();
|
|
var res = context.Posts.Include(p => p.Services).FirstOrDefault(p => p.Id == post.Id);
|
|
res.Name = post.Name;
|
|
res.Services = context.Services.Where(s => post.Services.Contains(s.Id)).ToList();
|
|
context.SaveChanges();
|
|
return Ok(new PostViue(res));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return BadRequest(ex.Message);
|
|
}
|
|
}
|
|
[HttpDelete("delete/{Id}")]
|
|
public IActionResult delete([FromRoute] int Id)
|
|
{
|
|
try
|
|
{
|
|
using var context = new beautySalonContext();
|
|
var res = context.Posts.FirstOrDefault(p => p.Id == Id);
|
|
if (res != null)
|
|
{
|
|
context.Posts.Remove(res);
|
|
context.SaveChanges();
|
|
}
|
|
if (res == null)
|
|
{
|
|
return BadRequest(new NullReferenceException());
|
|
}
|
|
return Ok(new PostViue(res));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return BadRequest(ex.Message);
|
|
}
|
|
}
|
|
}
|
|
}
|