我是EF和LINQ的初學者,我想根據產品ID檢索類別列表(帶過濾器)。EF:如何解決多對多關係(涉及一些過濾)
所以,我有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);
其中SearchCategories
用於重複使用一些代碼,看起來像下面
IQueryable<Category> SearchCategories(MyFilter filter, IQueryable<Category> source = null)
{
source = source ?? this.dbContext.Categories;
return source.Where(cat => [...filtering...]);
}
雖然這看起來沒問題,我想稍微優化一下,在SelectMany
(使用SelectMany
內部的SearchCategories
)內部進行篩選...但我無法使其工作。我試過,但給我錯誤
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
裏面的類別?
謝謝!
我認爲你的代碼中有一個你不能擁有的錯字.SelectMany(cat => prod.Categories)你應該有.SelectMany(prod => prod.Categories)。 –
對,它是固定的! – Learner