using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TestAppRuna.API; using TestAppRuna.Entities; namespace TestAppRuna.Services { public class CartService : ICartService { public CartService(ShopDbContext shopDbContext) { this.DB = shopDbContext; } public ShopDbContext DB { get; } public async Task CreateOrUpdateCart(CartCreateUpdateModel model) { Cart cart = await DB.Carts .Where(Q => Q.CustomerID == model.CustomerID && Q.ProductID == model.ProductID) .FirstOrDefaultAsync(); if (cart == null) { cart = new Cart { ProductID = model.ProductID, CustomerID = model.CustomerID, }; DB.Carts.Add(cart); } cart.Quantity = model.Quantity; await DB.SaveChangesAsync(); return true; } public async Task DeleteCart(CartDeleteModel model) { var data = await DB.Carts .Where(Q => Q.CustomerID == model.CustomerID && Q.ProductID == model.ProductID) .FirstOrDefaultAsync(); if (data == null) { return false; } DB.Carts.Remove(data); await DB.SaveChangesAsync(); return true; } public async Task> Get() { var query = from cart in DB.Carts join product in DB.Products on cart.ProductID equals product.ProductID join customer in DB.Customers on cart.CustomerID equals customer.CustomerID select new CartCustomerListItem { ProductID = cart.ProductID, ProductName = product.Name, ProductPrice = product.Price, CustomerEmail = customer.Email, CustomerName = customer.Name, Quantity = cart.Quantity, }; var data = await query.ToListAsync(); return data; } public async Task> GetFromCustomer(Guid customerId) { var data = await DB.Carts .AsNoTracking() .Where(Q => Q.CustomerID == customerId) .Select(Q => new CartListItem { ProductID = Q.ProductID, ProductName = Q.Product.Name, ProductPrice = Q.Product.Price, Quantity = Q.Quantity }).ToListAsync(); return data; } public async Task HasCustomerID(Guid customerId) { return await DB.Customers .AsNoTracking() .Where(Q => Q.CustomerID == customerId) .AnyAsync(); } public async Task HasProductID(Guid productId) { return await DB.Products .AsNoTracking() .Where(Q => Q.ProductID == productId) .AnyAsync(); } } }