Skip to content

Commit 5331e82

Browse files
committed
BaseRepository + ProductRepository
Add update method to process multiple entity updates prior to saving changes
1 parent adee69a commit 5331e82

16 files changed

Lines changed: 108 additions & 52 deletions

Controllers/Models/Requests/ShipRequest.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ public class ShipRequest
55
/// <summary>
66
/// List of order ID's
77
/// </summary>
8-
/// <example>1,2,3</example>
8+
/// <example>[1,2,3]</example>
99
public required List<int> OrderIds { get; set; }
1010
/// <summary>
1111
/// Date shipped

Controllers/Models/Responses/RegionsResponse.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ public class RegionsResponse
77
/// <summary>
88
/// List of global regions
99
/// </summary>
10-
/// <example>Central America,Western Europe,British Isles</example>
10+
/// <example>"Central America,Western Europe,British Isles"</example>
1111
public IEnumerable<RegionDto> Regions { get; set; } = new List<RegionDto>();
1212
}
1313
}

Controllers/OrderController.cs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using AutoMapper;
22
using Microsoft.AspNetCore.Authorization;
3+
using Microsoft.AspNetCore.Http.HttpResults;
34
using Microsoft.AspNetCore.Mvc;
45
using NorthWindAPI.Controllers.Models.Requests;
56
using NorthWindAPI.Controllers.Models.Responses;
@@ -12,13 +13,15 @@ namespace NorthWindAPI.Controllers
1213
public class OrderController(
1314
IOrderService orderService,
1415
ICustomerService customerService,
16+
IProductService productService,
1517
IUserService employeeService,
1618
IMapper mapper,
1719
ILogger<OrderController> logger
1820
) : ControllerBase
1921
{
2022
private readonly IOrderService _orderService = orderService;
2123
private readonly ICustomerService _customerService = customerService;
24+
private readonly IProductService _productService = productService;
2225
private readonly IUserService _employeeService = employeeService;
2326

2427
private readonly IMapper _mapper = mapper;
@@ -119,6 +122,9 @@ public async Task<ActionResult<OrderResponse>> Create(NewOrderRequest newOrder)
119122
{
120123
try
121124
{
125+
//Update product stock - subtract quantity ordered from units in stock
126+
await _productService.RemoveStock(newOrder.OrderDetail);
127+
122128
var order = await _orderService.ProcessNewOrder(newOrder);
123129

124130
if (order == null)
@@ -136,9 +142,9 @@ public async Task<ActionResult<OrderResponse>> Create(NewOrderRequest newOrder)
136142

137143
return orderResponse;
138144
}
139-
catch
145+
catch(Exception ex)
140146
{
141-
return Forbid();
147+
return Forbid(ex.Message);
142148
}
143149
}
144150

@@ -259,10 +265,20 @@ public async Task<ActionResult<ShipOptionResponse>> Carriers()
259265
[ProducesResponseType(typeof(NoContentResult), StatusCodes.Status200OK)]
260266
[ProducesResponseType(typeof(BadRequestResult), StatusCodes.Status400BadRequest)]
261267
[ProducesResponseType(typeof(UnauthorizedResult), StatusCodes.Status401Unauthorized)]
268+
[ProducesResponseType(typeof(NotFoundResult), StatusCodes.Status404NotFound)]
262269
[Authorize]
263270
[HttpDelete("{id}")]
264271
public async Task<ActionResult> Delete(int id)
265272
{
273+
var order = await _orderService.FindOrder(id);
274+
if(order == null)
275+
{
276+
return NotFound();
277+
}
278+
279+
//Update product stock - add quantity ordered from order to be deleted
280+
await _productService.ReplaceStock(order.Items);
281+
266282
var result = await _orderService.RemoveOrder(id);
267283
if (!result)
268284
{

Data/DB/Northwind_data.sqlite

0 Bytes
Binary file not shown.

Data/Repositories/BaseRepository.cs

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@ public async Task<T> AddEntityAsync(T entity)
3838
/// Delete entity and save changes to database
3939
/// </summary>
4040
/// <param name="id"></param>
41-
/// <returns></returns>
4241
public async Task<bool> RemoveEntityAsync(int id)
4342
{
4443
var entity = await _dbSet.FindAsync(id);
@@ -54,7 +53,7 @@ public async Task<bool> RemoveEntityAsync(int id)
5453
}
5554
catch
5655
{
57-
return true;
56+
return false;
5857
}
5958

6059
return true;
@@ -64,7 +63,6 @@ public async Task<bool> RemoveEntityAsync(int id)
6463
/// Deletes entity and does not save the changes. Call this method to delete all dependencies and finish with RemoveEntityAsync()
6564
/// </summary>
6665
/// <param name="id"></param>
67-
/// <returns></returns>
6866
public async Task<bool> RemoveDependentEntityAsync(int id)
6967
{
7068
var entity = await _dbSet.FindAsync(id);
@@ -98,19 +96,39 @@ public async Task<bool> RemoveDependentEntityAsync(int id)
9896
{
9997
await _context.SaveChangesAsync();
10098
}
101-
catch (DbUpdateConcurrencyException)
99+
catch (DbUpdateConcurrencyException ex)
102100
{
103101
if (!await _dbSet.AnyAsync(x => x.Id == id))
104102
{
105103
return entity;
106104
}
107105
else
108106
{
109-
throw;
107+
throw new Exception(ex.Message + " : Error updating entity");
110108
}
111109
}
112110

113111
return await _dbSet.FindAsync(id);
114112
}
113+
114+
/// <summary>
115+
/// Updates multiple entities before saving because EntityFramework doesn't handle many single updates well
116+
/// </summary>
117+
/// <param name="entities"></param>
118+
public async Task UpdateMultipleEntityAsync(IEnumerable<T> entities)
119+
{
120+
var entityIdCollection = entities.Select(x => x.Id);
121+
var entitiesToUpdate = _dbSet.Where(x => entityIdCollection.Contains(x.Id)).ToList();
122+
entitiesToUpdate.ForEach(x => _dbSet.Entry(x).State = EntityState.Modified);
123+
124+
try
125+
{
126+
await _context.SaveChangesAsync();
127+
}
128+
catch (DbUpdateConcurrencyException ex)
129+
{
130+
throw new Exception(ex.Message + " : Error updating multiple entity");
131+
}
132+
}
115133
}
116134
}

Data/Repositories/BaselAltRepository.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ public async Task<bool> RemoveEntityAsync(string id)
6565
/// Deletes entity and does not save the changes. Call this method to delete all dependencies and finish with RemoveEntityAsync()
6666
/// </summary>
6767
/// <param name="id"></param>
68-
/// <returns></returns>
68+
6969
public async Task<bool> RemoveDependentEntityAsync(string id)
7070
{
7171
var entity = await _dbSet.FindAsync(id);

Data/Repositories/OrderRepository.cs

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -108,22 +108,5 @@ public async Task<bool> DeleteOrder(int id)
108108
}
109109

110110
#endregion
111-
112-
113-
114-
//public async Task<List<object>> FindFullOrder(int id)
115-
//{
116-
// var sqlRaw =
117-
// "SELECT * " +
118-
// "FROM " +
119-
// "FROM [Order] o " +
120-
// "JOIN [Employee] e ON e.Id = o.EmployeeId " +
121-
// "JOIN [OrderDetail] od ON o.Id = od.OrderId " +
122-
// "JOIN [Product] p ON p.Id = od.ProductId " +
123-
// $"WHERE o.Id = {id}";
124-
125-
// var query = FormattableStringFactory.Create(sqlRaw);
126-
// return await _context.Database.SqlQuery<object>(query).ToListAsync();
127-
//}
128111
}
129112
}

Data/Repositories/ProductRepository.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,11 @@ public async Task<Product> UpdateProduct(int id, Product prod)
7676
return await _baseProductRepo.UpdateEntityAsync(id, prod);
7777
}
7878

79+
public async Task UpdateMultipleProducts(IEnumerable<Product> prods)
80+
{
81+
await _baseProductRepo.UpdateMultipleEntityAsync(prods);
82+
}
83+
7984
#endregion
8085
}
8186
}

Data/RepositoryInterfaces/IBaseRepository.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ public interface IBaseRepository<T> where T : class
88
public Task<bool> RemoveEntityAsync(int id);
99
public Task<bool> RemoveDependentEntityAsync(int id);
1010
public Task<T?> UpdateEntityAsync(int id, T entity);
11+
public Task UpdateMultipleEntityAsync(IEnumerable<T> entities);
1112

1213
}
1314
}

Data/RepositoryInterfaces/IProductRespository.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,6 @@ public interface IProductRepository
1111
public Task<Category> FindCategory(int categoryId);
1212
public Task<Supplier> FindSupplier(int supplierId);
1313
public Task<Product> UpdateProduct(int id, Product prod);
14+
public Task UpdateMultipleProducts(IEnumerable<Product> prods);
1415
}
1516
}

0 commit comments

Comments
 (0)