using Application.Domain.Entities; using Infrastructure.Data; using Infrastructure.Extensions; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.ComponentModel.DataAnnotations; using System.Linq; namespace IoTCenter.Api.Controllers { [ApiVersion("1.0")] [Route("api/v{version:apiVersion}/[controller]/[action]")] [ApiController] public class ProductController : ControllerBase { private readonly IRepository _productRepo; private readonly IRepository _deviceRepo; public ProductController(IRepository productRepo, IRepository deviceRepo) { this._productRepo = productRepo; this._deviceRepo = deviceRepo; } [HttpPost] public ActionResult GetProducts() { try { var model = this._productRepo.ReadOnlyTable() .OrderBy(o => o.DisplayOrder) .ThenBy(o => o.Name) .ToList() .Select(o => new { o.Id, o.Name, o.Number, o.Image, o.DisplayOrder, Count = _deviceRepo.ReadOnlyTable().Count(d => d.ProductId == o.Id) }); return Ok(model); } catch (Exception ex) { ex.PrintStack(); return Problem(ex.Message); } } [HttpPost] public ActionResult GetProduct([Required]string number) { try { var model = this._productRepo.ReadOnlyTable() .Include(o => o.Devices) .ThenInclude(o => o.Data) .Include(o => o.Devices) .ThenInclude(o => o.Node) .Where(o => o.Number == number) .FirstOrDefault(); model.Devices = model.Devices.OrderBy(o => o.NodeId).ToList(); return Ok(model); } catch (Exception ex) { ex.PrintStack(); return Problem(ex.Message); } } } }