EF不能直接支持执行存储过程,于是使用转化成执行SQL语句的形式,却怎么也获取不到output的值,折腾的好久,终于解决了,分享下曲折的经历:
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[].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() FROM [Vote] WHERE TitleId = @titleId AND BlockId = @blockId END
其实很简单了,这样就可以获取到返回值@num为output的值了,首先是写成了如下的形式,一直获取的是null值,一直报错:
db.Database.ExecuteSqlCommand("EXEC [AddVote] @blockId,@titleId,@typeId,@num", paramArray.ToArray());
记得"EXEC [AddVote] @blockId,@titleId,@typeId,@num" 标明@num为out类型参数,太不智能了⊙﹏⊙b汗 谢谢以下链接的:http://www.tuicool.com/articles/zquiYf