首页 > 解决方案 > Nopcommerce 4.2 - 如何获取 _ProductBox 部分视图的类别

问题描述

我将此代码添加到 ProductModelFactory.cs 中 ProductCategories = product.ProductCategories.ToList()

public virtual IEnumerable<ProductOverviewModel> PrepareProductOverviewModels(IEnumerable<Product> products,
            bool preparePriceModel = true, bool preparePictureModel = true,
            int? productThumbPictureSize = null, bool prepareSpecificationAttributes = false,
            bool forceRedirectionAfterAddingToCart = false)
        {
            if (products == null)
                throw new ArgumentNullException(nameof(products));

            var models = new List<ProductOverviewModel>();
            foreach (var product in products)
            {
                var model = new ProductOverviewModel
                {
                    Id = product.Id,
                    Name = _localizationService.GetLocalized(product, x => x.Name),
                    ShortDescription = _localizationService.GetLocalized(product, x => x.ShortDescription),
                    FullDescription = _localizationService.GetLocalized(product, x => x.FullDescription),
                    SeName = _urlRecordService.GetSeName(product),
                    Sku = product.Sku,
                    ProductType = product.ProductType,
                    MarkAsNew = product.MarkAsNew &&
                        (!product.MarkAsNewStartDateTimeUtc.HasValue || product.MarkAsNewStartDateTimeUtc.Value < DateTime.UtcNow) &&
                        (!product.MarkAsNewEndDateTimeUtc.HasValue || product.MarkAsNewEndDateTimeUtc.Value > DateTime.UtcNow),
                    ProductCategories = product.ProductCategories.ToList()
            };

现在刷新第二次页面时出现错误:

$exception {“为警告'Microsoft.EntityFrameworkCore.Infrastructure.LazyLoadOnDisposedContextWarning生成错误:在关联的DbContext被释放后,尝试延迟加载实体类型'ProductCategoryProxy'上的导航属性'Category'。'。可以抑制此异常或通过将事件 ID 'CoreEventId.LazyLoadOnDisposedContextWarning' 传递给 'DbContext.OnConfiguring' 或 'AddDbContext' 中的 'ConfigureWarnings' 方法来记录。"} System.InvalidOperationException

_ProductBox.cshtml

<div class="category">


                @foreach (var item in Model.ProductCategories)
                {
                    @item.Category.Name
                }

            </div>

标签: c#sql-serverdependency-injectionnopcommerce.net-core-2.2

解决方案


由于上下文被释放,产品类别不能被延迟加载。ProductCategories您可以通过在加载Product列表时包含 来解决此问题。大概是在ProductService你调用PrepareProductOverviewModels方法之前的某个地方。为此,请将 添加Include(navigationPropertyPath)到表中。这会强制直接加载属性。

示例ProductService

productRepository.Table.Include("ProductCategories")

或者,如果您不想在 中编辑默认方法,则使用自定义服务调用ProductService替换product.ProductCategories.ToList()

ProductCategories = _productService.GetProductCategoriesForProduct(product);

在您的ProductService中,您应该像这样创建此方法:

public virtual ProductCategories GetProductCategoriesForProduct(Product product)
{
    var resultProduct = _productRepository.Table.Include("ProductCategories")
        .FirstOrDefault(x => x.Id == product.Id);
    
    if(resultProduct != null)
        return resultProduct.ProductCategories.ToList();
    else
        return null; // Product not found, return null or empty list.
}

推荐阅读