Исключение произошло: clr /System.invalidoperationExcept /> system.private.corelib.dll, но не обрабатывался в коде пользователя: 'Недостаточная операция
. Соединение закрыто.
private readonly ILogger _logger;
private readonly DBContext _dbContext;
private const string CartSessionKey = "CartId";
private string ShoppingCartId { get; set;}
public ShoppingCartController(ILogger logger, DBContext dBContext)
{
_logger = logger;
_dbContext = dBContext;
}
public async void AddToCart(int id)
{
ShoppingCartId = GetCartID();
// Bottom line code breaks with the InvalidOperationException
Cart cart = await _dbContext.Carts.FirstOrDefaultAsync(c => c.CartId == ShoppingCartId && c.ProductId == id);
if (cart == null)
{
// If cart is null then we create a new cart
Cart newCart = new Cart
{
ProductId = id,
CartId = ShoppingCartId,
Product = await _dbContext.Products.FirstOrDefaultAsync(p => p.ProductId == id),
Count = 1,
CreatedDate = DateTime.Now,
};
await _dbContext.Carts.AddAsync(newCart);
}
else
{
cart.Count++;
}
await _dbContext.SaveChangesAsync();
}
private string GetCartID()
{
if(HttpContext.Session.Keys.Contains(CartSessionKey) == false)
{
if (!string.IsNullOrWhiteSpace(HttpContext.User.Identity.Name))
{
HttpContext.Session.SetString(CartSessionKey,HttpContext.User.Identity.Name);
}
else
{
Guid tempCartId = Guid.NewGuid();
HttpContext.Session.SetString(CartSessionKey, tempCartId.ToString());
}
}
return HttpContext.Session.GetString(CartSessionKey);
}
}
< /code>
dashboard.cshtml
@foreach(var prod in @ViewBag.Products)
{
@prod.ProductName
More Details
// This is where it would add the product to cart
Add to cart
}
< /code>
cart.cs
public class Cart
{
public int Id { get; set; }
public int Count { get; set; }
public string CartId { get; set; }
public DateTime CreatedDate { get; set; }
public int ProductId { get; set; }
public virtual Product Product { get; set; }
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... stem-priva