2011-01-13 18 views
3

我有一個樹形結構的分類表(Id,MasterId) 我想選擇屬於某個分類和所有子分類的所有產品。在實體框架中選擇分類樹

今天我使用這個SQL查詢的工作原理,但我想添加分頁,這將是一個純粹的LINQ查詢更容易。我使用實體框架4.

@Count int = 100, 
@CategoryId int 

with mq as 
(
    select c.Id as parent, c.Id as child 
    from dbo.Categories c 
    where c.Id = @CategoryId 
    union all 
    select q.child, c.Id 
    from mq q 
    inner join dbo.Categories c on q.child = c.MasterId 
) 

select top (@Count) P.* from Products P 
inner join ProductToCategory PC ON(PC.ProductId = P.Id) 
where PC.CategoryId in (
    select child from mq 
) 
and P.PublishStatus = 1 
order by P.PublishedDate DESC; 

任何想法如何獲得具有分頁(當前頁,每頁產品,總產品數數)上提供了很好的LINQ查詢?

回答

1

這是遞歸/ hiearchical查詢與表表達式。 EF不提供對此類查詢的支持。如果您想通過單向往返數據庫來接收數據,則必須將其包裝在存儲過程中,並將該過程導入到實體框架模型中。使用table expressions and ROW_NUMBER().

+0

有沒有辦法用Expressions實現這一點?像[this](http://stackoverflow.com/a/15636530/75500)? – Shimmy 2015-09-26 19:49:19

0

時,有一個想法

尋呼在SQL也是可能的。我沒有測試過,所以不要責怪,如果它不工作:P

var ids = context.TreeItems.Where(x => x.Id == parentId).Select(x => (int?)x.Id); 

    var tmp = ids; 
    while (true) 
    { 
     IQueryable<int?> localIds = tmp; 
     var subIds = context.TreeItems.Where(x => ids.Contains(x.ParentId)).Select(x => (int?)x.Id); 
    if (subIds.Any()) 
    { 
     tmp = subIds; 
     ids = ids.Union(subIds); 
      } 
    else 
     break; 
} 

    var allSubItems = context.TreeItems.Where(x => ids.Contains(x.Id)); 
+0

這將需要多次往返服務器。 – Shimmy 2015-09-26 19:42:38