简体   繁体   中英

Transform SQL query with recursion into LINQ

I'm stuck on a task where I have to transform a Stored Procedure into a LINQ query.

The model:

  • AccountSet: Account table with columns ' AccountId ', ' ParentAccountId ' (references an ' AccountId ') and ' Name '
  • ContactSet: Contact table with columns ' ParentCustomerId ' (references an Account via ' AccountId ')

The Stored Procedure:

  1. It should search for all accounts with the given id
  2. Search all parents (recursive) for the accounts found in step 1
  3. Fetch all contacts that have a ParentCustomerId matching an 'AccountId' found in step 2
CREATE PROCEDURE [dbo].[sp_GetContactsForCompany]
(      
       @projectid AS UNIQUEIDENTIFIER
) 
AS WITH recursion ( AccountId, Name, ParentAccountId ) 
    AS ( 
            SELECT AccountId, Name, ParentAccountId
            FROM dbo.AccountBase
            WHERE AccountId = @projectid

            UNION ALL

            SELECT a.AccountId, a.Name, a.ParentAccountId
            FROM dbo.AccountBase AS a 
            INNER JOIN recursion AS b ON a.ParentAccountId = b.AccountId 
        )
SELECT ContactId, FullName
FROM dbo.ContactBase
WHERE ParentCustomerId IN ( 
        SELECT AccountId
        FROM recursion 
)
ORDER BY FullName

LINQ:

from a in allAccs
where a.AccountId == id
select a;

This gives me all the accounts with the given id. But now I have no idea how to apply the join and recursion.

Any hint would be great.

You have to use AsHierarchy() method.

Check this article: http://www.scip.be/index.php?Page=ArticlesNET18#AsHierarchy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM