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

116 lines
3.6 KiB
C#

using Microsoft.AspNetCore.Mvc;
using RDBMS_lab4.Models;
using RDBMS_lab4.ViewModels;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace RDBMS_lab4.Controllers
{
[Route("api/[controller]")]
public class TimetablesController : Controller
{
public TimetablesController()
{
}
[HttpGet("get")]
public IActionResult get()
{
try
{
using var context = new beautySalonContext();
var res = context.Timetables.Select(b => new TimetableViue(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.Timetables.FirstOrDefault(b => b.Id == Id);
if (res == null)
{
return Ok(null);
}
return Ok(new TimetableViue(res));
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPost("create")]
public IActionResult create([FromBody] TimetableViue timetable)
{
try
{
using var context = new beautySalonContext();
var res = context.Timetables.Add(new()
{
Date = (DateTime)timetable.Date,
Buyerid = (int)(timetable.Buyerid),
Serviceid = (int)(timetable.Serviceid),
Workerid = (int)(timetable.Workerid)
});
context.SaveChanges();
if (res == null)
{
return BadRequest(new NullReferenceException());
}
return Ok(new TimetableViue(res.Entity));
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPut("update")]
public IActionResult update([FromBody] TimetableViue timetable)
{
try
{
using var context = new beautySalonContext();
var res = context.Timetables.FirstOrDefault(b => b.Id == timetable.Id);
res.Date = (DateTime)timetable.Date;
res.Buyerid = (int)(timetable.Buyerid);
res.Serviceid = (int)(timetable.Serviceid);
res.Workerid = (int)(timetable.Workerid);
context.SaveChanges();
return Ok(new TimetableViue(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.Timetables.FirstOrDefault(b => b.Id == Id);
if (res != null)
{
context.Timetables.Remove(res);
context.SaveChanges();
}
if (res == null)
{
return BadRequest(new NullReferenceException());
}
return Ok(new TimetableViue(res));
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
}
}