I have a cart which can have many products and a product can be in many carts I want to add product to the cart but I'm confused how I should do it? Is saving in the CartProduct
table right or something else if someone can explain to me how this works because I'm lost.
Cart class:
public class Cart
{
public int Id { get; set; }
public int ProductCount { get; set; }
public AppUser User { get; set; }
public List<CartProduct> CartProduct { get; set; }
}
Product class:
public partial class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
public decimal CostToMake { get; set; }
public decimal FinalPrice { get; set; }
public int? OrderId { get; set; }
public int? CartId { get; set; }
public virtual Order Order { get; set; }
public List<CartProduct> CartProduct { get; set; }
}
CartProduct
class:
public class CartProduct
{
public int CartId { get; set; }
public int ProductId { get; set; }
public Cart Cart { get; set; }
public Product Product { get; set; }
}
Car service:
public class SqlCart : ISqlCart
{
private ManagerZContext _dbContext;
public SqlCart(ManagerZContext dbContext)
{
_dbContext = dbContext;
}
public Cart AddProductToCart(Product product, Cart cart)
{
List<CartProduct> cartList = _dbContext.CartProduct.Where(cp => cp.CartId == cart.Id).ToList();
cartList.Add(product);
cart.CartProduct =
cart.ProductCount = cartList.Count();
_dbContext.Attach(cart).State = EntityState.Modified;
_dbContext.SaveChanges();
return new Cart();
}
public Cart CreateCart(AppUser user)
{
Cart cart = new Cart();
cart.User = user;
_dbContext.Carts.Add(cart);
return new Cart();
}
public Cart GetCart(AppUser user)
{
Cart cart = _dbContext.Carts.Where(c => c.User == user).FirstOrDefault();
List<CartProduct> cartList = _dbContext.CartProduct.Where(cp => cp.CartId == cart.Id).ToList();
cart.CartProduct = cartList;
return cart;
}
}
I'm confused what to do in the Cart service to add products to the cart?
question from:
https://stackoverflow.com/questions/65870454/save-data-with-many-to-many-relationship-ef-core 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…