如何使用LINQ从父子关系表中获取数据?

时间:2015-01-30 08:21:25

标签: sql-server linq asp.net-mvc-4 entity-framework-6

我有像Projects ==>这样的架构版本==>冲刺 01 Project01 Null 02 Version01 01 03 Sprint01 02 04 sprint02 02 05 Version02 01 06 Sprint03 05 07 Sprint04 05 08 Project02 Null 所以.......

我想检索所有SprintsId,所以我只是将Id(sprint / Version / Project的主键)传递给服务,基于Ids,如果它是ProjectId(这里是01)我想要检索所有版本(这里是02,05),然后找到SprintsId(03,04,06,07),如果是VersionsId(这里是05)我想要所有SprintsId(06,07)

1 个答案:

答案 0 :(得分:0)

我使用SQL存储过程找到解决方案。使用存储过程它不太复杂

CREATE PROCEDURE [dbo].[USP_Project]
( 
@ID INT
)
AS 
BEGIN
    DECLARE @PROJECT_LEVEL INT =0

    -- IF PROJECT LEVEL IS PROJECT

    SELECT @PROJECT_LEVEL=COUNT(ID) FROM PROJECTS WHERE ID=@ID AND PARENTID IS NULL 
    IF(@PROJECT_LEVEL=1)
    BEGIN  
            SELECT  PROJ.id AS PROJECT_ID,PROJ.Title  ,VER.ID AS VERSION_ID,VER.Title as [Version], SPRI.ID AS SPRINT_ID,SPRI.Title as [Sprint]
            FROM PROJECTS AS PROJ ,PROJECTS AS VER,PROJECTS AS SPRI
            WHERE  PROJ.ID=@ID AND VER.PARENTID=@ID AND SPRI.PARENTID=VER.ID
     END 

     -- IF PROJECT LEVEL IS VERSION
    SELECT   @PROJECT_LEVEL= COUNT(VER.ID)
    FROM        PROJECTS AS PROJ ,PROJECTS AS VER 
    WHERE       VER.PARENTID=PROJ.ID AND PROJ.PARENTID IS NULL AND VER.ID=@ID

    IF(@PROJECT_LEVEL>0)
    BEGIN 
            SELECT PROJ.id AS PROJECT_ID,PROJ.Title  ,VER.ID AS VERSION_ID,VER.Title as [Version], SPR.ID AS SPRINT_ID,SPR.Title as [Sprint]
            FROM PROJECTS AS PROJ  ,PROJECTS AS VER ,PROJECTS AS SPR
            WHERE  VER.ID=@ID AND SPR.PARENTID=@ID AND VER.PARENTID=PROJ.ID
    END 

     -- IF PROJECT LEVEL IS SPRINT

    SELECT @PROJECT_LEVEL=  COUNT(SPR.ID)
    FROM        PROJECTS AS PROJ ,PROJECTS AS VER ,PROJECTS AS SPR
    WHERE     SPR.PARENTID=VER.ID AND VER.PARENTID=PROJ.ID AND PROJ.PARENTID IS NULL AND SPR.ID=@ID 

    IF(@PROJECT_LEVEL>0)
    BEGIN  
            SELECT  PROJ.id AS PROJECT_ID,PROJ.Title  ,VER.ID AS VERSION_ID,VER.Title  as [Version] , SPR.ID AS SPRINT_ID,SPR.Title as [Sprint]
                    FROM PROJECTS AS PROJ ,PROJECTS AS VER ,PROJECTS AS SPR 
                    WHERE  SPR.ID=@ID AND SPR.PARENTID=VER.ID AND VER.PARENTID=PROJ.ID
    END
END