【发布时间】:2021-10-13 13:59:42
【问题描述】:
我浏览了一堆答案,并试图让代码正常工作,但看不到按 _productBundlesItemsRepository 表分组的方法
这是我正在查看的查询
return _productBundlesRepository.Table.Join(_productBundleItemsRepository.Table,
pbr => pbr.Id,
pbir => pbir.BundleId,
(pbr, pbir) => new { Bundle = pbr, BundleItem = pbir})
.Where(x => x.BundleItem.ProductId == productId && x.BundleItem.Visible == true && x.Bundle.Active == true).Select(x => x.Bundle).ToList();
我想也许我可以做这样的事情
.OrderByDescending(x => x.BundleItem.Count()) 但该选项不可用
我还尝试了一些方法,比如在这样的新语句中获取链接到捆绑包的项目数
new { Bundle = pbr, BundleItem = pbir, Count = GetProductBundleItems(pbr.Id).Count})
然后我收到这样的错误
System.NotSupportedException:LINQ to Entities 无法识别方法“System.Collections.Generic.List”
我不太确定如何订购由捆绑包中包含的捆绑包项目数量返回的捆绑包。
更新我根据@StriplingWarrior 的回答使用了一些修改过的代码,但似乎这不起作用,因为多个捆绑包可以包含相同的项目。 即一个捆绑包是 2 包,另一个捆绑包是 4 包,两者都使用相同的物品。 这是我更新的代码
var bundleItems = _productBundleItemsRepository.Table
.Where(bundleItem => bundleItem.ProductId == productId
&& bundleItem.Visible == true);
return _productBundlesRepository.Table
.Select(bundle => new BundleWithCount { pb = bundle, count = bundleItems.Count(bundleItem => bundleItem.BundleId == bundle.Id) })
.Where(x => x.pb.Active == true && x.count > 0).OrderByDescending(x => x.count).Select(x => x.pb)
.ToList();
与
internal class BundleWithCount
{
public int count { get; set; }
public ProductBundle pb { get; set; }
}
有人知道我哪里出错了吗?
谢谢
【问题讨论】:
-
“多个捆绑包可以包含同一个项目”是什么意思?如果一个 BundleItem 有一个 BundleId,这是否意味着关系是多对一的?即使没有,您也需要澄清什么“行不通”?你有错误吗?结果与您的预期不同?需要更多详细信息。
-
我明白了@StriplingWarrior 谢谢:)