无法访问导航属性上的项目数

时间:2018-03-11 10:28:00

标签: ef-code-first automapper entity-framework-core

我不确定此问题是自动映射问题还是实体框架问题。

我在viewmodel中从导航属性ProductCount获取产品数量时遇到问题。返回的值始终为"0"。如果该功能有效,则会在没有产品的类别上返回"no",在包含15种产品的类别上返回"15"

viewmodel:

public class ViewModelProductCategory
{
    public int Id { get; set; }
    public int? ParentId { get; set; }
    public string Title { get; set; }
    public int SortOrder { get; set; }

    public ViewModelProductCategory ParentCategory { get; set; }
    public IEnumerable<ViewModelProductCategory> Children { get; set; }
    public IEnumerable<ViewModelProduct> Products { get; set; }

    public string ProductCount
    {
        get
        {
            return Products != null
                ? Products.Count().ToString()
                : "no";
        }
    }
}

显示产品数量:

@model List<MyStore.Models.ViewModels.ViewModelProductCategory>
@foreach (var item in Model)
{   
    @item.Title has @item.ProductCount product(s).
}

我还尝试在视图中使用@item.Products.Count(),但这始终会返回0

这是视图模型的填充方式:

// Getting the categories
List<ProductCategory> DbCategories = _context.ProductCategories
                        .Include(e => e.Children).ToList().OrderBy(o => o.SortOrder)
                        .Where(e => e.ParentId == null).ToList();
// Mapping to ViewModel
List<ViewModelProductCategory> MapCategory = 
    _mapper.Map<List<ProductCategory>, List<ViewModelProductCategory>>(DbCategories);

映射:

CreateMap<ProductCategory, ViewModelProductCategory>()
            .ForMember(dst => dst.Products, opt => opt.MapFrom(
                src => src.ProductInCategory.Select(pc => pc.Product)));

ProductInCategory是类别和产品之间的链接表:

public class ProductInCategory
// A linking table for which products belongs to which categories
{
    public int Id { get; set; }
    public int ProductId { get; set; }
    public int ProductCategoryId { get; set; }
    public int SortOrder { get; set; }

    // Nav.props.:
    public Product Product { get; set; }
    public ProductCategory ProductCategory { get; set; }
}

为什么我不能获得产品数量?

修改

在评论的@IvanStoev的帮助下,我将查询更改为:

//get all categories, so we have each and every child in Context
        List<ProductCategory> DbCategories = _context.ProductCategories
                        .Include(e => e.Children)
                        .Include(e => e.ProductInCategory)
                            .ThenInclude(p => p.Product)
                        .ToList().OrderBy(o => o.SortOrder)
                        .Where(e => e.ParentId == null).ToList();

现在它有效!耶!

0 个答案:

没有答案
相关问题