Repository pattern implemented

This commit is contained in:
2019-12-19 21:20:20 +01:00
parent fc11be2baf
commit eff21e30c5
7 changed files with 128 additions and 111 deletions

View File

@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System.Net; using System.Net;
using H_Plus_Sports.Models; using H_Plus_Sports.Models;
using H_Plus_Sports.Contracts;
namespace HPlusSportsAPI.Controllers namespace HPlusSportsAPI.Controllers
{ {
@ -11,28 +12,28 @@ namespace HPlusSportsAPI.Controllers
[Route("api/Customers")] [Route("api/Customers")]
public class CustomersController : Controller public class CustomersController : Controller
{ {
private readonly H_Plus_SportsContext _context; private readonly ICustomerRepository _customerRepository;
public CustomersController(H_Plus_SportsContext context) public CustomersController( ICustomerRepository customerRepository)
{ {
_context = context; _customerRepository = customerRepository;
} }
private bool CustomerExists(int id) private async Task<bool> CustomerExists(int id)
{ {
return _context.Customer.Any(e => e.CustomerId == id); return await _customerRepository.Exist(id);
} }
[HttpGet] [HttpGet]
[Produces(typeof(DbSet<Customer>))] [Produces(typeof(DbSet<Customer>))]
public IActionResult GetCustomer() public IActionResult GetCustomer()
{ {
var results = new ObjectResult(_context.Customer) var results = new ObjectResult(_customerRepository.GetAll())
{ {
StatusCode = (int)HttpStatusCode.OK StatusCode = (int)HttpStatusCode.OK
}; };
Request.HttpContext.Response.Headers.Add("X-Total-Count", _context.Customer.Count().ToString()); Request.HttpContext.Response.Headers.Add("X-Total-Count", _customerRepository.GetAll().Count().ToString());
return results; return results;
} }
@ -46,7 +47,7 @@ namespace HPlusSportsAPI.Controllers
return BadRequest(ModelState); return BadRequest(ModelState);
} }
var customer = await _context.Customer.SingleOrDefaultAsync(m => m.CustomerId == id); var customer = await _customerRepository.Find(id);
if (customer == null) if (customer == null)
{ {
@ -70,16 +71,15 @@ namespace HPlusSportsAPI.Controllers
return BadRequest(); return BadRequest();
} }
_context.Entry(customer).State = EntityState.Modified;
try try
{ {
await _context.SaveChangesAsync(); await _customerRepository.Update(customer);
return Ok(customer); return Ok(customer);
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!CustomerExists(id)) if (!await CustomerExists(id))
{ {
return NotFound(); return NotFound();
} }
@ -99,8 +99,7 @@ namespace HPlusSportsAPI.Controllers
return BadRequest(ModelState); return BadRequest(ModelState);
} }
_context.Customer.Add(customer); await _customerRepository.Add(customer);
await _context.SaveChangesAsync();
return CreatedAtAction("GetCustomer", new { id = customer.CustomerId }, customer); return CreatedAtAction("GetCustomer", new { id = customer.CustomerId }, customer);
} }
@ -114,16 +113,14 @@ namespace HPlusSportsAPI.Controllers
return BadRequest(ModelState); return BadRequest(ModelState);
} }
var customer = await _context.Customer.SingleOrDefaultAsync(m => m.CustomerId == id); if (! await CustomerExists(id))
if (customer == null)
{ {
return NotFound(); return NotFound();
} }
_context.Customer.Remove(customer); await _customerRepository.Remove(id);
await _context.SaveChangesAsync();
return Ok(customer); return Ok();
} }
} }
} }

View File

@ -1,32 +1,32 @@
using System.Linq; using System.Threading.Tasks;
using System.Threading.Tasks; using H_Plus_Sports.Contracts;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using H_Plus_Sports.Models; using H_Plus_Sports.Models;
namespace HPlusSportsAPI.Controllers namespace H_Plus_Sports.Controllers
{ {
[Produces("application/json")] [Produces("application/json")]
[Route("api/OrderItems")] [Route("api/OrderItems")]
public class OrderItemsController : Controller public class OrderItemsController : Controller
{ {
private readonly H_Plus_SportsContext _context; private readonly IOrderItemRepository _orderItems;
public OrderItemsController(H_Plus_SportsContext context) public OrderItemsController(IOrderItemRepository orderItems)
{ {
_context = context; _orderItems = orderItems;
} }
private bool OrderItemExists(int id) private async Task<bool> OrderItemExists(int id)
{ {
return _context.OrderItem.Any(e => e.OrderItemId == id); return await _orderItems.Exists(id);
} }
[HttpGet] [HttpGet]
[Produces(typeof(DbSet<OrderItem>))] [Produces(typeof(DbSet<OrderItem>))]
public IActionResult GetOrderItem() public IActionResult GetOrderItem()
{ {
return new ObjectResult(_context.OrderItem); return new ObjectResult(_orderItems.GetAll());
} }
[HttpGet("{id}")] [HttpGet("{id}")]
@ -38,7 +38,7 @@ namespace HPlusSportsAPI.Controllers
return BadRequest(ModelState); return BadRequest(ModelState);
} }
var orderItem = await _context.OrderItem.SingleOrDefaultAsync(m => m.OrderItemId == id); var orderItem = await _orderItems.Find(id);
if (orderItem == null) if (orderItem == null)
{ {
@ -62,22 +62,20 @@ namespace HPlusSportsAPI.Controllers
return BadRequest(); return BadRequest();
} }
_context.Entry(orderItem).State = EntityState.Modified;
try try
{ {
await _context.SaveChangesAsync(); await _orderItems.Update(orderItem);
return Ok(orderItem); return Ok(orderItem);
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!OrderItemExists(id)) if (!await OrderItemExists(id))
{ {
return NotFound(); return NotFound();
} }
else else
{ {
throw; return BadRequest();
} }
} }
} }
@ -91,8 +89,7 @@ namespace HPlusSportsAPI.Controllers
return BadRequest(ModelState); return BadRequest(ModelState);
} }
_context.OrderItem.Add(orderItem); await _orderItems.Add(orderItem);
await _context.SaveChangesAsync();
return CreatedAtAction("GetOrderItem", new { id = orderItem.OrderItemId }, orderItem); return CreatedAtAction("GetOrderItem", new { id = orderItem.OrderItemId }, orderItem);
} }
@ -106,16 +103,14 @@ namespace HPlusSportsAPI.Controllers
return BadRequest(ModelState); return BadRequest(ModelState);
} }
var orderItem = await _context.OrderItem.SingleOrDefaultAsync(m => m.OrderItemId == id); if (! await OrderItemExists(id))
if (orderItem == null)
{ {
return NotFound(); return NotFound();
} }
_context.OrderItem.Remove(orderItem); await _orderItems.Remove(id);
await _context.SaveChangesAsync();
return Ok(orderItem); return Ok();
} }
} }
} }

View File

@ -1,32 +1,32 @@
using System.Linq; using System.Threading.Tasks;
using System.Threading.Tasks; using H_Plus_Sports.Contracts;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using H_Plus_Sports.Models; using H_Plus_Sports.Models;
namespace HPlusSportsAPI.Controllers namespace H_Plus_Sports.Controllers
{ {
[Produces("application/json")] [Produces("application/json")]
[Route("api/Orders")] [Route("api/Orders")]
public class OrdersController : Controller public class OrdersController : Controller
{ {
private readonly H_Plus_SportsContext _context; private readonly IOrderRepository _orders;
public OrdersController(H_Plus_SportsContext context) public OrdersController(IOrderRepository orders)
{ {
_context = context; _orders = orders;
} }
private bool OrderExists(int id) private async Task<bool> OrderExists(int id)
{ {
return _context.Order.Any(e => e.OrderId == id); return await _orders.Exists(id);
} }
[HttpGet] [HttpGet]
[Produces(typeof(DbSet<Order>))] [Produces(typeof(DbSet<Order>))]
public IActionResult GetOrder() public IActionResult GetOrder()
{ {
return new ObjectResult(_context.Order); return new ObjectResult(_orders.GetAll());
} }
[HttpGet("{id}")] [HttpGet("{id}")]
@ -38,7 +38,7 @@ namespace HPlusSportsAPI.Controllers
return BadRequest(ModelState); return BadRequest(ModelState);
} }
var order = await _context.Order.SingleOrDefaultAsync(m => m.OrderId == id); var order = await _orders.Find(id);
if (order == null) if (order == null)
{ {
@ -62,22 +62,20 @@ namespace HPlusSportsAPI.Controllers
return BadRequest(); return BadRequest();
} }
_context.Entry(order).State = EntityState.Modified;
try try
{ {
await _context.SaveChangesAsync(); await _orders.Update(order);
return Ok(order); return Ok(order);
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!OrderExists(id)) if (!await OrderExists(id))
{ {
return NotFound(); return NotFound();
} }
else else
{ {
throw; return BadRequest();
} }
} }
} }
@ -91,8 +89,21 @@ namespace HPlusSportsAPI.Controllers
return BadRequest(ModelState); return BadRequest(ModelState);
} }
_context.Order.Add(order); try
await _context.SaveChangesAsync(); {
await _orders.Add(order);
}
catch (DbUpdateException)
{
if (!await OrderExists(order.OrderId))
{
return NotFound();
}
else
{
return BadRequest();
}
}
return CreatedAtAction("GetOrder", new { id = order.OrderId }, order); return CreatedAtAction("GetOrder", new { id = order.OrderId }, order);
} }
@ -106,16 +117,14 @@ namespace HPlusSportsAPI.Controllers
return BadRequest(ModelState); return BadRequest(ModelState);
} }
var order = await _context.Order.SingleOrDefaultAsync(m => m.OrderId == id); if (!await OrderExists(id))
if (order == null)
{ {
return NotFound(); return NotFound();
} }
_context.Order.Remove(order); await _orders.Remove(id);
await _context.SaveChangesAsync();
return Ok(order); return Ok();
} }
} }
} }

View File

@ -1,33 +1,32 @@
using System.Linq; using System.Threading.Tasks;
using System.Threading.Tasks; using H_Plus_Sports.Contracts;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using H_Plus_Sports.Models; using H_Plus_Sports.Models;
namespace HPlusSportsAPI.Controllers namespace H_Plus_Sports.Controllers
{ {
[Produces("application/json")] [Produces("application/json")]
[Route("api/Products")] [Route("api/Products")]
public class ProductsController : Controller public class ProductsController : Controller
{ {
private readonly H_Plus_SportsContext _context; private readonly IProductRepository _products;
public ProductsController(H_Plus_SportsContext context) public ProductsController(IProductRepository products)
{ {
_context = context; _products = products;
} }
private bool ProductExists(string id) private async Task<bool> ProductExists(string id)
{ {
return _context.Product.Any(e => e.ProductId == id); return await _products.Exists(id);
} }
[HttpGet] [HttpGet]
[Produces(typeof(DbSet<Product>))] [Produces(typeof(DbSet<Product>))]
public IActionResult GetProduct() public IActionResult GetProduct()
{ {
return new ObjectResult(_context.Product); return new ObjectResult(_products.GetAll());
} }
[HttpGet("{id}")] [HttpGet("{id}")]
@ -39,7 +38,7 @@ namespace HPlusSportsAPI.Controllers
return BadRequest(ModelState); return BadRequest(ModelState);
} }
var product = await _context.Product.SingleOrDefaultAsync(m => m.ProductId == id); var product = await _products.Find(id);
if (product == null) if (product == null)
{ {
@ -63,22 +62,20 @@ namespace HPlusSportsAPI.Controllers
return BadRequest(); return BadRequest();
} }
_context.Entry(product).State = EntityState.Modified;
try try
{ {
await _context.SaveChangesAsync(); await _products.Update(product);
return Ok(product); return Ok(product);
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!ProductExists(id)) if (!await ProductExists(id))
{ {
return NotFound(); return NotFound();
} }
else else
{ {
throw; return BadRequest();
} }
} }
} }
@ -92,20 +89,19 @@ namespace HPlusSportsAPI.Controllers
return BadRequest(ModelState); return BadRequest(ModelState);
} }
_context.Product.Add(product);
try try
{ {
await _context.SaveChangesAsync(); await _products.Add(product);
} }
catch (DbUpdateException) catch (DbUpdateException)
{ {
if (ProductExists(product.ProductId)) if (!await ProductExists(product.ProductId))
{ {
return new StatusCodeResult(StatusCodes.Status409Conflict); return NotFound();
} }
else else
{ {
throw; return BadRequest();
} }
} }
@ -121,16 +117,14 @@ namespace HPlusSportsAPI.Controllers
return BadRequest(ModelState); return BadRequest(ModelState);
} }
var product = await _context.Product.SingleOrDefaultAsync(m => m.ProductId == id); if (!await ProductExists(id))
if (product == null)
{ {
return NotFound(); return NotFound();
} }
_context.Product.Remove(product); await _products.Remove(id);
await _context.SaveChangesAsync();
return Ok(product); return Ok();
} }
} }
} }

View File

@ -1,32 +1,32 @@
using System.Linq; using System.Threading.Tasks;
using System.Threading.Tasks; using H_Plus_Sports.Contracts;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using H_Plus_Sports.Models; using H_Plus_Sports.Models;
namespace HPlusSportsAPI.Controllers namespace H_Plus_Sports.Controllers
{ {
[Produces("application/json")] [Produces("application/json")]
[Route("api/Salespersons")] [Route("api/Salespersons")]
public class SalespersonsController : Controller public class SalespersonsController : Controller
{ {
private readonly H_Plus_SportsContext _context; private readonly ISalespersonRepository _salespeople;
public SalespersonsController(H_Plus_SportsContext context) public SalespersonsController(ISalespersonRepository salespeople)
{ {
_context = context; _salespeople = salespeople;
} }
private bool SalespersonExists(int id) private async Task<bool> SalespersonExists(int id)
{ {
return _context.Salesperson.Any(e => e.SalespersonId == id); return await _salespeople.Exists(id);
} }
[HttpGet] [HttpGet]
[Produces(typeof(DbSet<Salesperson>))] [Produces(typeof(DbSet<Salesperson>))]
public IActionResult GetSalesperson() public IActionResult GetSalesperson()
{ {
return new ObjectResult(_context.Salesperson); return new ObjectResult(_salespeople.GetAll());
} }
[HttpGet("{id}")] [HttpGet("{id}")]
@ -38,7 +38,7 @@ namespace HPlusSportsAPI.Controllers
return BadRequest(ModelState); return BadRequest(ModelState);
} }
var salesperson = await _context.Salesperson.SingleOrDefaultAsync(m => m.SalespersonId == id); var salesperson = await _salespeople.Find(id);
if (salesperson == null) if (salesperson == null)
{ {
@ -62,22 +62,20 @@ namespace HPlusSportsAPI.Controllers
return BadRequest(); return BadRequest();
} }
_context.Entry(salesperson).State = EntityState.Modified;
try try
{ {
await _context.SaveChangesAsync(); await _salespeople.Update(salesperson);
return Ok(salesperson); return Ok(salesperson);
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!SalespersonExists(id)) if (!await SalespersonExists(id))
{ {
return NotFound(); return NotFound();
} }
else else
{ {
throw; return BadRequest();
} }
} }
} }
@ -91,8 +89,21 @@ namespace HPlusSportsAPI.Controllers
return BadRequest(ModelState); return BadRequest(ModelState);
} }
_context.Salesperson.Add(salesperson); try
await _context.SaveChangesAsync(); {
await _salespeople.Add(salesperson);
}
catch (DbUpdateException)
{
if (!await SalespersonExists(salesperson.SalespersonId))
{
return NotFound();
}
else
{
return BadRequest();
}
}
return CreatedAtAction("GetSalesperson", new { id = salesperson.SalespersonId }, salesperson); return CreatedAtAction("GetSalesperson", new { id = salesperson.SalespersonId }, salesperson);
} }
@ -106,16 +117,14 @@ namespace HPlusSportsAPI.Controllers
return BadRequest(ModelState); return BadRequest(ModelState);
} }
var salesperson = await _context.Salesperson.SingleOrDefaultAsync(m => m.SalespersonId == id); if (!await SalespersonExists(id))
if (salesperson == null)
{ {
return NotFound(); return NotFound();
} }
_context.Salesperson.Remove(salesperson); await _salespeople.Remove(id);
await _context.SaveChangesAsync();
return Ok(salesperson); return Ok();
} }
} }
} }

View File

@ -5,6 +5,10 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.0"> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.0">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>

View File

@ -2,7 +2,9 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using H_Plus_Sports.Contracts;
using H_Plus_Sports.Models; using H_Plus_Sports.Models;
using H_Plus_Sports.Repositories;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.HttpsPolicy;
@ -27,6 +29,13 @@ namespace H_Plus_Sports
// This method gets called by the runtime. Use this method to add services to the container. // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
services.AddScoped<ICustomerRepository, CustomerRepository>();
services.AddScoped<IOrderRepository, OrderRepository>();
services.AddScoped<IOrderItemRepository, OrderItemRepository>();
services.AddScoped<IProductRepository, ProductRepository>();
services.AddScoped<ISalespersonRepository, SalespersonRepository>();
services.AddMvc();
services.AddControllers(); services.AddControllers();
var connection = "Server=tcp:hsportsoeman.database.windows.net,1433;Initial Catalog=H_Plus_Sports;Persist Security Info=False;User ID=saTfoman;Password=Jes@lin78;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"; var connection = "Server=tcp:hsportsoeman.database.windows.net,1433;Initial Catalog=H_Plus_Sports;Persist Security Info=False;User ID=saTfoman;Password=Jes@lin78;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
services.AddDbContext<H_Plus_SportsContext>(options => options.UseSqlServer(connection)); services.AddDbContext<H_Plus_SportsContext>(options => options.UseSqlServer(connection));