1. 程式人生 > >EF中執行儲存過程,獲取output返回值

EF中執行儲存過程,獲取output返回值

<span style="color: rgb(75, 75, 75); font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13px; line-height: 20.8px;">EF不能直接支援執行儲存過程,於是使用轉化成執行SQL語句的形式,卻怎麼也獲取不到output的值,折騰的好久,終於解決了,分享下曲折的經歷:</span>
public int AddVote(int titleId, int blockId, int typeId)
        {
            List<SqlParameter> paramArray = new List<SqlParameter>();
            paramArray.Add(new SqlParameter("@titleId", titleId));
            paramArray.Add(new SqlParameter("@blockId", blockId));
            paramArray.Add(new SqlParameter("@typeId", typeId));
            SqlParameter param = new SqlParameter("@num", SqlDbType.Int);
            param.Direction = ParameterDirection.Output;
            paramArray.Add(param);
                        
            using (RPDBContext db = new RPDBContext())
            {
                try
                {
                    db.Database.ExecuteSqlCommand("EXEC [AddVote] @blockId,@titleId,@typeId,@num out", paramArray.ToArray());
                }
                catch (Exception ex)
                {
                    throw;
                }
                int result = (int)paramArray[3].Value;
                return result;
            }
        }
儲存過程測試例項:
USE [HY_ReplyComment]
GO
/****** 物件:  StoredProcedure [dbo].[AddVote]    指令碼日期: 06/10/2014 22:27:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:    <Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[AddVote] 
    @blockId int,
    @titleId int,
    @typeId int,
    @num int output
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    SELECT @num = Count(1) FROM [Vote] WHERE TitleId = @titleId AND BlockId = @blockId

END