【问题标题】:Select category tree in Entity Framework在实体框架中选择类别树
【发布时间】:2011-01-13 11:34:28
【问题描述】:

我有一个具有树结构 (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 查询?

【问题讨论】:

    标签: c# linq entity-framework


    【解决方案1】:

    这是带有表表达式的递归/分层查询。 EF 不支持此类查询。如果您想通过单次往返 DB 接收数据,则必须将其包装在存储过程中并将该过程导入您的实体框架模型。

    使用table expressions and ROW_NUMBER().时也可以在SQL中进行分页

    【讨论】:

    • 有没有办法通过表达式实现这一点? this 之类的东西?
    【解决方案2】:

    有个主意。我还没有测试过,所以如果它不起作用,请不要责怪: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));
    

    【讨论】:

    • 这需要多次往返服务器。
    猜你喜欢
    • 1970-01-01
    • 2022-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多