using KSPMasterKey.Server.Data; using KSPMasterKey.Shared; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace KSPMasterKey.Server.Controllers { [Route("api/[controller]")] [ApiController] public class CustomerController : ControllerBase { private readonly DataContext _context; public CustomerController(DataContext context) { _context = context; } [HttpGet("{id}")] public async Task GetCustomer(int id) { Customer? customer = new(); if (id == 0) { return BadRequest(); } else { customer = await _context.Customers.SingleOrDefaultAsync(c => c.Id == id); } if (customer == null) { return NotFound(); } else { return Ok(customer); } } [HttpGet] public async Task GetCustomersAsync() { var customers = new List(); if (_context != null && _context.Customers != null) { //int id = _context.Customers.Count(); //var entity = _context.Customers.Where(x => x.Id == id); //await _context.Entry(entity).ReloadAsync(); customers = await _context.Customers.ToListAsync(); } List sorted = customers.OrderBy(x => x.Name).ToList(); return Ok(sorted); } [HttpPost] public async void SaveCustomerAsync([FromBody] CustomerRequest request) { int id = request.Id; Customer? customer = request.customer; if (id == 0) { var newCust = new Customer() { Name = customer.Name, Address1 = customer.Address1, Address2 = customer.Address2, City = customer.City, State = customer.State, ZipCode = customer.ZipCode, Phone = customer.Phone }; if (_context != null && _context.Customers != null) { _context.Add(newCust); await _context.SaveChangesAsync(); } } else { if (_context != null && _context.Customers != null) { var updateCust = _context.Customers.FirstOrDefault(c => c.Id == id); if (updateCust != null) { updateCust.Name = customer.Name; updateCust.Address1 = customer.Address1; updateCust.Address2 = customer.Address2; updateCust.City = customer.City; updateCust.State = customer.State; updateCust.ZipCode = customer.ZipCode; updateCust.Phone = customer.Phone; _context.Customers.Update(updateCust); await _context.SaveChanges(); } } } } } }