我是 EF 和 LINQ 的初学者,我想按产品 ID 检索类别列表(带过滤器)。
所以,我之间有多对多的关系Product * <---> * Category
,我使用以下代码:
var categList = dbContext.Products
.Where(prod => prod.PROD_UID == 1234)
.SelectMany(prod => prod.Categories)
.Distinct();
categList = SearchCategories(filter, categList);
categList = SortCategories(filter, categList);
categList = PageCategories(filter, categList);
whereSearchCategories
用于重用一些代码,如下所示
IQueryable<Category> SearchCategories(MyFilter filter, IQueryable<Category> source = null)
{
source = source ?? this.dbContext.Categories;
return source.Where(cat => [...filtering...] );
}
虽然这看起来不错,但我想对其进行稍微优化,在内部过滤SelectMany
(利用SearchCategories
inside SelectMany
)......但我无法让它工作。我试过这个,但给了我错误
var categList = dbContext.Products
.Where(prod => prod.PROD_UID == 1234)
.SelectMany(cat => SearchCategories(filter, prod.Categories.AsQueryable()).AsEnumerable());
// throws LINQ to Entities does not recognize the method 'SearchCategories'
我如何过滤里面的类别SelectMany
?
谢谢!