创建递归Linq到实体查询? (像递归CTE一样) [英] Create Recursive Linq to Entities query? (Like recursive CTE)
问题描述
我有一个Web应用程序,具有简单的用户组树结构,并寻找一种方式来查询以下内容:
I have a web application with simple tree structure of usergroups and looking for a way to query for such things as:
- 顶级父母
- 任何级别的所有子组(子女等等)
- 所有父组(我的父母,父母的父母等)
我正在使用MS SQL,因此在DB中编写我需要的选择并保存他们作为存储过程。
I'm using MS SQL so its not a big problem to write selections I need in DB and to save them as stored procedures.
但是有没有办法使用EntityToSql创建这样的查询?
以下是使用TSQL查询的示例:
Here is example of the TSQL query I use:
DECLARE @userGroupId uniqueidentifier
DECLARE @searchTerm nvarchar(20)
SET @userGroupId = '00000000-0000-0000-0000-000000000000'
Set @searchTerm = 'test'
;WITH n(lvl,id,ParentUserGroupId,FullName) AS (
SELECT 1,id,ParentUserGroupId,FullName FROM UserGroups where
id in (select UserGroupId
FROM Users WHERE login like '%'+@searchTerm+'%')
UNION ALL
SELECT n.lvl+1, nplus1.id,nplus1.ParentUserGroupId, nplus1.FullName
FROM UserGroups as nplus1,n WHERE n.ParentUserGroupId = nplus1.id
)
SELECT DIStinct id,FullName
FROM n where ParentUserGroupId = @userGroupId OR
((@userGroupId IS NULL OR @userGroupId = '00000000-0000-0000-0000-000000000000')
AND ParentUserGroupId IS NULL)
推荐答案
不,您不能在ESQL或Linq-to-entities中创建此类递归查询。
No you cannot create such recursive query in ESQL or in Linq-to-entities.
您可以直接使用EF或ADO.NET调用存储过程,或者如果您使用.NET 4.5,如果使用EDMX,则可以将查询包装在表值功能,将功能导入到EDMX中,并在Linq-to-entities查询中使用该功能。
You can call your stored procedure with EF or ADO.NET directly or if you have .NET 4.5 and if you are using EDMX, you can wrap your query in table valued function, import the function into your EDMX and use it in Linq-to-entities queries.
这篇关于创建递归Linq到实体查询? (像递归CTE一样)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!