-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathCartRepository.cs
86 lines (70 loc) · 2.63 KB
/
CartRepository.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using AspnetRunBasics.Data;
using AspnetRunBasics.Entities;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;
using AspnetRunBasics.Repositories.Interfaces;
namespace AspnetRunBasics.Repositories
{
public class CartRepository : ICartRepository
{
protected readonly AspnetRunContext _dbContext;
public CartRepository(AspnetRunContext dbContext)
{
_dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
}
public async Task<Cart> GetCartByUserName(string userName)
{
var cart = _dbContext.Carts
.Include(c => c.Items)
.ThenInclude(i => i.Product)
.FirstOrDefault(c => c.UserName == userName);
if (cart != null)
return cart;
// if it is first attempt create new
var newCart = new Cart
{
UserName = userName
};
_dbContext.Carts.Add(newCart);
await _dbContext.SaveChangesAsync();
return newCart;
}
public async Task AddItem(string userName, int productId, int quantity = 1, string color = "Black")
{
var cart = await GetCartByUserName(userName);
cart.Items.Add(
new CartItem
{
ProductId = productId,
Color = color,
Price = _dbContext.Products.FirstOrDefault(p => p.Id == productId).Price,
Quantity = quantity
}
);
_dbContext.Entry(cart).State = EntityState.Modified;
await _dbContext.SaveChangesAsync();
}
public async Task RemoveItem(int cartId, int cartItemId)
{
var cart = _dbContext.Carts
.Include(c => c.Items)
.FirstOrDefault(c => c.Id == cartId);
if (cart != null)
{
var removedItem = cart.Items.FirstOrDefault(x => x.Id == cartItemId);
cart.Items.Remove(removedItem);
_dbContext.Entry(cart).State = EntityState.Modified;
await _dbContext.SaveChangesAsync();
}
}
public async Task ClearCart(string userName)
{
var cart = await GetCartByUserName(userName);
cart.Items.Clear();
_dbContext.Entry(cart).State = EntityState.Modified;
await _dbContext.SaveChangesAsync();
}
}
}