Files
Vidly2/Vidly/Controllers/Api/CustomersController.cs

87 lines
2.4 KiB
C#

using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Vidly.Dtos;
using Vidly.Models;
namespace Vidly.Controllers.Api
{
public class CustomersController : ApiController
{
private ApplicationDbContext _context;
public CustomersController()
{
_context = new ApplicationDbContext();
}
// GET /Api/Customers
public IEnumerable<CustomerDto> GetCustomers()
{
return _context.Customers.ToList().Select(Mapper.Map<Customer,CustomerDto>);
}
// GET /Api/Customers/1
public CustomerDto GetCustomer(int Id)
{
var customer = _context.Customers.SingleOrDefault(c => c.Id == Id);
if (customer == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
return Mapper.Map<Customer,CustomerDto>(customer);
}
// POST /Api/Customers
[HttpPost]
public CustomerDto CreateCustomer(CustomerDto customerDto)
{
if (!ModelState.IsValid)
throw new HttpResponseException(HttpStatusCode.BadRequest);
var customer = Mapper.Map<CustomerDto, Customer>(customerDto);
_context.Customers.Add(customer);
_context.SaveChanges();
customerDto.Id = customer.Id;
return customerDto;
}
// PUT /Api/Customers/1
[HttpPut]
public void UpdateCustomer(int Id,CustomerDto customerDto)
{
if (!ModelState.IsValid)
throw new HttpResponseException(HttpStatusCode.BadRequest);
var customerInDb = _context.Customers.SingleOrDefault(c => c.Id == Id);
if (customerInDb == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
//Mapper.Map<CustomerDto, Customer>(customerDto, customerInDb);
Mapper.Map(customerDto, customerInDb);
_context.SaveChanges();
}
// DELETE /Api/Customers/1
[HttpDelete]
public void DeleteCustomer(int Id)
{
var customerInDb = _context.Customers.SingleOrDefault(c => c.Id == Id);
if (customerInDb == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
_context.Customers.Remove(customerInDb);
_context.SaveChanges();
}
}
}