c#查询类别并通过连接产品表计算其产品

时间:2017-12-19 20:39:43

标签: c# entity-framework linq

我可能会离开,但是一些谷歌搜索让我产生了这个问题:

VMCategory = from pc in _context.ProductCategories
            join pic in _context.ProductsInCategories
            on pc.Id equals pic.ProductCategoryId
            group pic by pc into x
            select new ViewModelProductCategory
            {
                Id = x.Key.Id,
                ParentId = x.Key.ParentId,
                Title = x.Key.Title,
                SortOrder = x.Key.SortOrder,
                NumOfProductsInThisCategory = x.Count(c => [SOMETHING IS MISSING])
            }).
            ToList();

我尝试使用实体模型中的类别项填充viewmodel列表,并计算每个类别中所有产品的数量。

我需要这种类型的结果(作为类别对象列表中的项目):

Id = 6                          (from ProductCategory)
ParentId = 4                    (from ProductCategory)
Title = "Example"               (from ProductCategory)
SortOrder = 2                   (from ProductCategory)
NumOfProductsInThisCategory = 7 (count products from ProductsInCategories)

这些是我的模特:

视图模型:

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

实体模型:

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

public class ProductInCategory
{
    public int Id { get; set; }
    public int ProductId { get; set; }
    public int ProductCategoryId { get; set; }
    public int SortOrder { get; set; }
}

2 个答案:

答案 0 :(得分:2)

如果您要加入,则可以GroupJoin进行GroupBy并且不需要VMCategory = from pc in _context.ProductCategories join pic in _context.ProductsInCategorieson pc.Id equals pic.ProductCategoryId into picj select new ViewModelProductCategory { Id = pc.Id, ParentId = pc.ParentId, Title = pc.Title, SortOrder = pc.SortOrder, NumOfProductsInThisCategory = picj.Count() }). ToList();

<div id="food-content" v-if="activeFood" v-cloak>

答案 1 :(得分:1)

可能有用的东西是与你的模特形成多对一的纽带。 因此,将您的实体模型更改为:

public class ProductCategory
{
    public int Id { get; set; }
    public int? ParentId { get; set; }
    public string Title { get; set; }
    public int SortOrder { get; set; }
    public List<ProductInCategory> ProductInCategory { get; set; }
}

public class ProductInCategory
{
    public int Id { get; set; }
    public int ProductId { get; set; }
    public int SortOrder { get; set; }
    public int ProductCategoryId { get; set; }
}

然后你能做的就是:

var ProductList = _context.ProductCategory.Include(p=> p.ProductInCategory).ToList()

简单明了,您有完整的类别列表,每个类别都包含其中所有产品的列表。 您可以在该变量的末尾抛出where子句来进行计数等。或甚至IF循环或Foreach循环来说foreach产品类别计数ProductInCategory。

一旦表格之间存在关系,就可以做到。

CAZ