ASPNetCore/TestAppRuna/API/CustomerController.cs

137 lines
4.0 KiB
C#

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(AuthenticationSchemes = "nanaoaccounts")]
public class CustomerController : ControllerBase
{
public CustomerController(ShopDbContext shopDbContext)
{
ShopDb = shopDbContext;
}
public ShopDbContext ShopDb { get; }
// GET: api/<CustomerController>
[HttpGet]
public async Task<IEnumerable<CustomerListItem>> 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/<CustomerController>/5
[HttpGet("{id}")]
public async Task<ActionResult<CustomerListItem>> 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/<CustomerController>
[HttpPost]
public async Task<ActionResult<string>> 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/<CustomerController>/5
[HttpPut("{id}")]
public async Task<ActionResult<string>> 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/<CustomerController>/5
[HttpDelete("{id}")]
public async Task<ActionResult<string>> 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; }
}
}