RDBMS/RDBMS_lab4/Controllers/WorkersController.cs
2024-05-12 17:52:28 +04:00

111 lines
3.2 KiB
C#

using Microsoft.AspNetCore.Mvc;
using RDBMS_lab4.Models;
using RDBMS_lab4.ViewModels;
namespace RDBMS_lab4.Controllers
{
[Route("api/[controller]")]
public class WorkersController : Controller
{
public WorkersController()
{
}
[HttpGet("get")]
public IActionResult get()
{
try
{
using var context = new beautySalonContext();
var res = context.Workers.Select(b => new WorkerViue(b)).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.Workers.FirstOrDefault(b => b.Id == Id);
if (res == null)
{
return Ok(null);
}
return Ok(new WorkerViue(res));
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPost("create")]
public IActionResult create([FromBody] WorkerViue worker)
{
try
{
using var context = new beautySalonContext();
var res = context.Workers.Add(new()
{
Name = worker.Name,
Postid = (int)worker.Postid
});
context.SaveChanges();
if (res == null)
{
return BadRequest(new NullReferenceException());
}
return Ok(new WorkerViue(res.Entity));
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPut("update")]
public IActionResult update([FromBody] WorkerViue worker)
{
try
{
using var context = new beautySalonContext();
var res = context.Workers.FirstOrDefault(b => b.Id == worker.Id);
res.Postid = (int)worker.Postid;
res.Name = worker.Name;
context.SaveChanges();
return Ok(new WorkerViue(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.Workers.FirstOrDefault(b => b.Id == Id);
if (res != null)
{
context.Workers.Remove(res);
context.SaveChanges();
}
if (res == null)
{
return BadRequest(new NullReferenceException());
}
return Ok(new WorkerViue(res));
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
}
}