using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using TestAppRuna.Entities; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace TestAppRuna.API { [Route("api/[controller]")] [ApiController] // [Authorize("nanaoaccounts")] public class CustomerController : ControllerBase { public CustomerController(ShopDbContext shopDbContext) { ShopDb = shopDbContext; } public ShopDbContext ShopDb { get; } // GET: api/ [HttpGet] public async Task> Get() { var data = await ShopDb.Customers.AsNoTracking() .AsNoTracking() .Select(Q => new CustomerListItem() { CustomerID = Q.CustomerID, Name = Q.Name, Email = Q.Email, }) .OrderBy(Q => Q.Name) .ToListAsync(); return data; } // GET api//5 [HttpGet("{id}")] public async Task> Get(Guid id) { var data = await ShopDb.Customers .AsNoTracking() .Where(Q => Q.CustomerID == id) .FirstOrDefaultAsync(); if(data == null) { return BadRequest(); } return new CustomerListItem() { CustomerID = data.CustomerID, Name = data.Name, Email = data.Email, }; } // POST api/ [HttpPost] public async Task> Post([FromBody] CustomerCreateUpdateModel model) { if(ModelState.IsValid == false) { return BadRequest(); } var customer = new Customer() { CustomerID = Guid.NewGuid(), Name = model.Name, Email = model.Email, }; ShopDb.Customers.Add(customer); await ShopDb.SaveChangesAsync(); return "OK"; } // PUT api//5 [HttpPut("{id}")] public async Task> Put(Guid id, [FromBody] CustomerCreateUpdateModel model) { if(ModelState.IsValid == false) { return BadRequest(); } var customer = await ShopDb.Customers .Where(Q => Q.CustomerID == id) .FirstAsync(); if (customer == null) { return NotFound(); } customer.Name = model.Name; customer.Email = model.Email; //ShopDb.Customers.Update(customer); await ShopDb.SaveChangesAsync(); return "OK"; } // DELETE api//5 [HttpDelete("{id}")] public async Task> Delete(Guid id) { var customer = await ShopDb.Customers .Where(Q => Q.CustomerID == id) .FirstAsync(); if (customer == null) { return NotFound(); } ShopDb.Customers.Remove(customer); await ShopDb.SaveChangesAsync(); return "OK"; } } public class CustomerListItem { public Guid CustomerID { get; set; } public string Name { get; set; } public string Email { get; set; } } public class CustomerCreateUpdateModel { [Required] [StringLength(255)] public string Name { get; set; } [Required] [StringLength(255)] public string Email { get; set; } } }