I have a web application with simple tree structure of usergroups and looking for a way to query for such things as:
- top level parent
- all child groups at any level(child of childs and etc)
- all parent groups (my parent, parent of parent etc)
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.
But is there a way to create such query with using just EntityToSql?
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)
No you cannot create such recursive query in ESQL or in 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.