Why can't Entity Framework see my Stored Procedure's column information?

后端 未结 10 1339
终归单人心
终归单人心 2020-12-02 14:54

I have the following stored procedure and when I attempt to Function Import it says my Stored Procedure returns no columns. What am I missing? Any Suggestions?

The

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-02 15:09

    I'd like to add something to Sudhanshu Singh's answer: It works very well, but if you have more complex structures, combine it with a table declaration.

    I have used the following successfully (place it at the very beginning of your stored procecure):

    CREATE PROCEDURE [EY].[MyStoredProc] 
    AS
    BEGIN
    
    SET NOCOUNT ON;
    
    IF (1=0) 
    BEGIN 
        SET FMTONLY OFF 
            BEGIN
                -- declaration + dummy query 
                -- to allow EF obtain complex data type:
                DECLARE @MyStoredProcResult TABLE(
                    ID      INT,
                    VendorName  VARCHAR(255),
                    ItemName    VARCHAR(255),
                    Type        VARCHAR(2),
                    Sequence    TINYINT
                    );
                SELECT * FROM @MyStoredProcResult WHERE (1=0)
            END
    END   
    
    -- your code follows here (SELECT ... FROM ...)
    -- this code must return the same columns/data types
    --
    -- if you require a temp table / table variable like the one above
    -- anyway, add the results during processing to @MyStoredProcResult
    -- and then your last statement in the SP can be
    -- SELECT * FROM @MyStoredProcResult
    END
    

    Note that the 1=0 guarantees that it never gets executed, but the EF deducts the structure from it.

    After you have saved your stored procedure, open the EDMX file in Visual Studio, refresh the data model, go to the Entity Frameworks model browser. In the model browser, locate your stored procedure, open up the "Edit Function Import" dialog, select "Returns a collection of ... Complex", then click on the button "Get Column Information".

    It should show up the structure as defined above. If it does, click on "Create New Complex Type", and it will create one with the name of the stored procedure, e.g. "MyStoredProc_Result" (appended by "_Result").

    Now you can select it in the combobox of "Returns a collection of ... Complex" on the same dialog.

    Whenever you need to update something, update the SP first, then you can come back to the Edit Function Import dialog and click on the "Update" button (you don't need to re-create everything from scratch).

提交回复
热议问题