System.Private.CoreLib.dll 中发生“System.InvalidOperationException”类型的异常

问题描述 投票:0回答:1

我不明白为什么在尝试将产品添加到数据库中的购物车时出现错误。我有一个产品想要添加到购物车。如果购物车不存在,那么我们创建一个新购物车并将其添加到数据库中。每次我们添加相同的产品时,计数都会增加 1。它应该用所述产品填充购物车,但我收到一条

Exception has occurred: CLR/System.InvalidOperationException An exception of type 'System.InvalidOperationException' occurred in System.Private.CoreLib.dll but was not handled in user code: 'Invalid operation. The connection is closed.'
错误消息。 ASP.NET Core MVC 8

ShoppingCartController.cs


    private readonly ILogger<ShoppingCartController> _logger;
    private readonly DBContext _dbContext;
    private const string CartSessionKey = "CartId";
    private string ShoppingCartId { get; set;}

    public ShoppingCartController(ILogger<ShoppingCartController> 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);
    }
}

仪表板.cshtml


<div class="d-flex">
    <div class="row rows-cols-4">
        @foreach(var prod in @ViewBag.Products)
        {
            <div class="card m-1" style="width: 18rem;">
                <img src="..." class="card-img-top" alt="...">
                <div class="card-body">
                    <h5 class="card-title">@prod.ProductName</h5>
                    <a class="btn btn-primary" asp-controller="Customer" asp-action="ProductDetails" asp-route-id="@prod.ProductId">More Details</a>
                    // This is where it would add the product to cart
                    <a class="btn btn-primary" asp-controller="ShoppingCart" asp-action="AddToCart" asp-route-id="@prod.ProductId">Add to cart</a>
                </div>
            </div>
        }
        
    </div>
</div>

购物车.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; }
}

c# .net asp.net-mvc
1个回答
0
投票

您有几个问题需要解决:

  1. 根据 Microsoft 的 EF 文档此处,您应该使用:
_dBContext.Carts.Add(newCart);

而不是

AddAsync()
AddAsync
仅应在非常特定的情况下使用,即当您有特殊的 sql 生成器需要异步访问数据库时。

  1. 异步方法永远不应该返回 void,它们应该始终返回
    Task
    。所以,你的方法签名应该是这样的:
public async Task AddToCart(int id)

看来,由于您的

async void
,EF 提前关闭了您的 DBContext 连接,这引发了上面的异常。

© www.soinside.com 2019 - 2024. All rights reserved.