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] public class ProductController : ControllerBase { public ShopDbContext DB { get; } public ProductController(ShopDbContext shopDbContext) { this.DB = shopDbContext; } // GET: api/ [HttpGet] public async Task>> Get() { var data = await DB.Products .AsNoTracking() .Select(Q => new ProductListItem() { ProductID = Q.ProductID, Name = Q.Name, Price = Q.Price }) .OrderBy(Q => Q.Name) .ToListAsync(); return data; } // GET api//5 [HttpGet("{id}")] public async Task> Get(Guid id) { var data = await DB.Products .AsNoTracking() .Where(Q => Q.ProductID == id) .Select(Q => new ProductListItem() { ProductID = Q.ProductID, Name = Q.Name, Price = Q.Price, }) .FirstOrDefaultAsync(); if (data == null) { return NotFound(); } return data; } // POST api/ [HttpPost] public async Task> Post([FromBody] ProductCreateUpdateModel model) { if(ModelState.IsValid == false) { return BadRequest(); } Product product = new Product { ProductID = Guid.NewGuid(), Name = model.Name, Price = model.Price, }; DB.Products.Add(product); await DB.SaveChangesAsync(); return "OK"; } // PUT api//5 [HttpPut("{id}")] public async Task> Put(Guid id, [FromBody] ProductCreateUpdateModel model) { if(ModelState.IsValid == false) { return BadRequest(); } var data = await DB.Products .Where(Q => Q.ProductID == id) .FirstOrDefaultAsync(); if(data == null) { return NotFound(); } data.Name = model.Name; data.Price = model.Price; await DB.SaveChangesAsync(); return "OK"; } // DELETE api//5 [HttpDelete("{id}")] public async Task> Delete(Guid id) { var data = await DB.Products .Where(Q => Q.ProductID == id) .FirstOrDefaultAsync(); if(data == null) { return NotFound(); } DB.Products.Remove(data); await DB.SaveChangesAsync(); return "OK"; } } public class ProductListItem { public Guid ProductID { get; set; } public string Name { get; set; } public decimal Price { get; set; } } public class ProductCreateUpdateModel { [Required] [StringLength(255)] public string Name { get; set; } [Required] [Range(double.Epsilon,double.MaxValue)] public decimal Price { get; set; } } }