9

我在 Sql Server 中有这个查询,我需要在 EntityFramework 中使用它,那么我怎样才能编写一个与此结果相同的 EntityFramwork 代码

WITH    cte AS
        (
        SELECT  *
        FROM    StockGroups
        WHERE   GroupParent ='Stationery' 
        UNION ALL
        SELECT  g.*
        FROM    StockGroups g
        JOIN    cte
        ON      g.GroupParent = cte.GroupName
        )
SELECT  *
FROM    cte

我不知道如何在 EF 中转换它,所以我尝试加入。

from a in db.StockGroups
join b in db.StockGroups on new { GroupParent = a.GroupParent } equals new { GroupParent = b.GroupName }
where
  b.GroupName == "Stationery"
select new {
  a.GroupName,
  a.GroupParent,
  Column1 = b.GroupName,
  Column2 = b.GroupParent
}

但结果不一样,和 CTE 一样递归。

4

5 回答 5

9

EF 不支持递归 CTE。使用视图或表值函数。

于 2012-11-23T19:55:08.697 回答
7

从其他专家那里得到关于 SO 的意见,我想出了自己的方法来实现这一点。

IEnumerable<StockGroup> sg = dbContext.ExecuteStoreQuery<StockGroup>(
                        @"WITH    q AS
                                    (
                                    SELECT  *
                                    FROM    LedgerGroups
                                    WHERE   GroupParent = 'Customers'
                                    UNION ALL
                                    SELECT  m.*
                                    FROM    LedgerGroups m
                                    JOIN    q
                                    ON      m.GroupParent = q.GroupName
                                    )
                            SELECT  *
                            FROM    q
                        ");
于 2012-11-23T20:20:14.440 回答
5

您不能在实体框架中使用 CTE 递归。

于 2012-11-23T19:54:53.920 回答
1

使用存储过程并通过 EF 调用该存储过程

于 2014-04-10T12:53:38.070 回答
1

我认为 LINQ 和 EF 都不支持递归 CTE。解决方案是将 CTE 公开为视图。有关使用 EF 代码优先和迁移的递归或分层查询的文章展示了如何使用 EF 代码优先迁移部署此类视图。使用 EF Code First 和迁移的递归或分层查询

原文来源: https ://stackoverflow.com/a/11929928/3850405

于 2017-09-14T14:01:17.127 回答