DbContext ExecuteSqlCommand-表值存储过程



我在从DbContext调用存储过程时遇到问题。存储过程接受一个表值参数。

程序的语法为:

ALTER PROCEDURE dbo.SaveResults
  @resultID int,
  @positiveResults AS dbo.PositiveResultTypes READONLY
AS

我有一个DataTable(dtResults),其中填充了该表类型的有效值。

我的呼叫代码是:

var resultsParam = new SqlParameter("@positiveResults", SqlDbType.Structured);
resultsParam.Value = dtResults;
resultsParam.TypeName = "PositiveResultTypes";
db.Database.ExecuteSqlCommand(
    "dbo.SaveResults", 
    new SqlParameter("@resultID", id),
    resultsParam);

这是失败的:

过程或函数"SaveResults"需要参数"@resultID",没有提供。

变量id是有效的,而不是此处的nullint,值1)。

我尝试将调用代码中的语法更改为"dbo.SaveResults @resultID @positiveResults",但没有更改结果。

为什么它没有看到这个参数?

编辑

SQL事件探查器显示此参数正确传递。。。

declare @p3 dbo.PositiveResultTypes 
insert into @p3 values(N'1')
insert into @p3 values(N'4')
insert into @p3 values(N'6')
exec sp_executesql N'dbo.SaveResults',N'@positiveResults [PositiveResultTypes] READONLY,@resultID int',@positiveResults=@p3,@resultID=1

但是,EXEC的这种语法在某种程度上是不正确的。当我对数据库执行此操作时,我会得到相同的结果:

(1 row(s) affected)
(1 row(s) affected)
(1 row(s) affected)
Msg 201, Level 16, State 4, Procedure SaveResults, Line 0
Procedure or function 'SaveResults' expects parameter '@resultID', which was not supplied.
using (SqlConnection con = new SqlConnection(cs))
{
    // Configure the SqlCommand and SqlParameter.
    SqlCommand sqlCmd = new SqlCommand("dbo.SaveResults", con);
    sqlCmd.CommandType = CommandType.StoredProcedure;
    SqlParameter tvpParam = sqlCmd.Parameters.AddWithValue("@positiveResults", dtResults); 
    //tell compiler that we are passing TVP
    tvpParam.SqlDbType = SqlDbType.Structured; 
    sqlCmd.Parameters.Add(new SqlParameter("@resultID", id));
    sqlCmd.ExecuteNonQuery();
}

将resultsparameter作为参数数组,将两个参数都添加到其中。然后在ExecuteSqlCommand方法中传递参数。

上面提到的错误之所以显示,是因为有两个sql参数传递给它,而只有一个sql参数可以传递给它。

最新更新