简体   繁体   English

将具有递归的SQL查询转换为LINQ

[英]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. 我陷入了必须将存储过程转换为LINQ查询的任务。

The model: 该模型:

  • AccountSet: Account table with columns ' AccountId ', ' ParentAccountId ' (references an ' AccountId ') and ' Name ' AccountSet:具有“ AccountId ”,“ ParentAccountId ”(引用“ AccountId ”)和“ 名称 ”列的帐户表
  • ContactSet: Contact table with columns ' ParentCustomerId ' (references an Account via ' AccountId ') ContactSet:带有“ ParentCustomerId ”列的联系表(通过“ AccountId ”引用一个帐户)

The Stored Procedure: 存储过程:

  1. It should search for all accounts with the given id 它应搜索具有给定ID的所有帐户
  2. Search all parents (recursive) for the accounts found in step 1 在所有父级(递归)中搜索在步骤1中找到的帐户
  3. Fetch all contacts that have a ParentCustomerId matching an 'AccountId' found in step 2 提取其ParentCustomerId与在步骤2中找到的“ AccountId”匹配的所有联系人
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: LINQ:

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

This gives me all the accounts with the given id. 这给了我所有具有给定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. 您必须使用AsHierarchy()方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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