using ASP.NET_WebAPI6.DTO; using ASP.NET_WebAPI6.Entities; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Net; namespace ASP.NET_WebAPI6.Controllers { [ApiController] [Route("api/[controller]")] public class UserController : ControllerBase { private readonly DBContext DBContext; public UserController(DBContext DBContext) { this.DBContext = DBContext; } [HttpGet("GetUsers")] public async Task<actionresult<list<userdto>>> Get() { var list = await DBContext.Users.Select( s => new UserDTO() { Id = s.Id, FirstName = s.FirstName, LastName = s.LastName, Username = s.Username, Password = s.Password, EnrollmentDate = s.EnrollmentDate } ).ToListAsync(); if (list.Count < 0) { return NotFound(); } else { return list; } } [HttpGet("GetUserById")] public async Task<actionresult<userdto>> GetUserById(int Id) { UserDTO User = await DBContext.Users.Select( s => new UserDTO() { Id = s.Id, FirstName = s.FirstName, LastName = s.LastName, Username = s.Username, Password = s.Password, EnrollmentDate = s.EnrollmentDate }) .FirstOrDefaultAsync(s => s.Id == Id); if (User == null) { return NotFound(); } else { return User; } } [HttpPost("InsertUser")] public async Task<httpstatuscode> InsertUser(UserDTO User) { var entity = new User() { Id = User.Id, FirstName = User.FirstName, LastName = User.LastName, Username = User.Username, Password = User.Password, EnrollmentDate = User.EnrollmentDate }; DBContext.Users.Add(entity); await DBContext.SaveChangesAsync(); return HttpStatusCode.Created; } [HttpPut("UpdateUser")] public async Task<httpstatuscode> UpdateUser(UserDTO User) { var entity = await DBContext.Users.FirstOrDefaultAsync(s => s.Id == User.Id); entity.FirstName = User.FirstName; entity.LastName = User.LastName; entity.Username = User.Username; entity.Password = User.Password; entity.EnrollmentDate = User.EnrollmentDate; await DBContext.SaveChangesAsync(); return HttpStatusCode.OK; } [HttpDelete("DeleteUser/{Id}")] public async Task<httpstatuscode> DeleteUser(int Id) { var entity = new User() { Id = Id }; DBContext.Users.Attach(entity); DBContext.Users.Remove(entity); await DBContext.SaveChangesAsync(); return HttpStatusCode.OK; } } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)