使用Entity Framework中的union和临时表进行查询的存储过程

时间:2014-08-20 14:04:39

标签: entity-framework stored-procedures

我有一个存储过程,它使用临时表和union来查询数据库:

ALTER PROCEDURE q_GetAllAttributesAndValuesByDocument(@IdDocument BIGINT)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT  
       AT.IDATRIBUTO,
       AT.NOMBREATRIBUTO,
       AD.VALORATRIBUTO
    INTO
       #TMP_ATTR
    FROM    
       ATRIBUTOS AT
    INNER JOIN 
       ATRIBUTOSXDOCUMENTO AD ON AT.IDATRIBUTO = AD.IDATRIBUTO
    WHERE 
       AD.IDDOCUMENTO2 = @IdDocument

    SELECT  
       TA.IDATRIBUTO AS Id,
       TA.NOMBREATRIBUTO AS Name,
       TA.VALORATRIBUTO AS Value
    FROM
       #TMP_ATTR TA

    UNION 

    SELECT  
       AT.IDATRIBUTO AS Id,
       AT.NOMBREATRIBUTO AS Name,
       '' AS Value
    FROM    
       ATRIBUTOS AT
    WHERE 
       IDATRIBUTO NOT IN (SELECT TA.IDATRIBUTO
                          FROM #TMP_ATTR TA)
END 

当我将此存储过程添加到我的Entity Framework模型时,不会创建复杂类型,EF只会从存储过程返回一个整数。

我该怎么办?

由于

1 个答案:

答案 0 :(得分:0)

尝试使用CTE而不是临时表。

ALTER PROCEDURE q_GetAllAttributesAndValuesByDocument(@IdDocument BIGINT)
AS
BEGIN
    SET NOCOUNT ON;

    WITH TMP_ATTR (Id, Name, Value)
    AS
    (
        SELECT  
           AT.IDATRIBUTO,
           AT.NOMBREATRIBUTO,
           AD.VALORATRIBUTO
        FROM    
           ATRIBUTOS AT
        INNER JOIN 
           ATRIBUTOSXDOCUMENTO AD ON AT.IDATRIBUTO = AD.IDATRIBUTO
        WHERE 
           AD.IDDOCUMENTO2 = @IdDocument
    )

    SELECT  
       TA.IDATRIBUTO AS Id,
       TA.NOMBREATRIBUTO AS Name,
       TA.VALORATRIBUTO AS Value
    FROM
       TMP_ATTR TA

    UNION 

    SELECT  
       AT.IDATRIBUTO AS Id,
       AT.NOMBREATRIBUTO AS Name,
       '' AS Value
    FROM    
       ATRIBUTOS AT
    WHERE 
       IDATRIBUTO NOT IN (SELECT TA.IDATRIBUTO
                          FROM TMP_ATTR TA)

然后从数据库更新模型。