Stored Procedure expects parameter: Parameter is shown in profiler …?
Question
I am calling a stored procedure from a DbContext
using SqlQuery()
. When I run the query I get the error Procedure or function 'p_Insert_Phones' expects parameter '@Number', which was not supplied.
What am I missing here? I see the @Number
parameter.
declare @p5 nvarchar(255)
set @p5=NULL
exec sp_executesql N'p_Insert_Phones',
N'@Number int,
@PhoneTypeId int,
@ReturnId nvarchar(255) output',
@Number=0,
@PhoneTypeId=0,
@ReturnId=@p5 output
select @p5
EDIT
Procedure definition
CREATE PROCEDURE [dbo].[p_Insert_Phones]
(
@Number int,
@PhoneTypeId int,
@ReturnId uniqueidentifier out
)
AS
DECLARE @id TABLE(
ReturnColId uniqueidentifier
)
BEGIN TRAN
INSERT INTO Phones ([Number],[PhoneTypeId])
OUTPUT inserted.Id
INTO @id
VALUES (@Number,@PhoneTypeId)
COMMIT TRAN
SET @ReturnId = (SELECT ReturnColId FROM @id)
Solution 2
You cannot call a stored procedure that is found in the database. The parameters that you provide will not be found by the stored procedure. I resolved the issue by including the stored procedure as the sql in the DbContext call.
var sqlInsert = "DECLARE @id TABLE(ReturnColId uniqueidentifier) " +
"BEGIN TRAN INSERT INTO Phones " +
"([Number],PhoneTypeId]) " +
"OUTPUT inserted.Id " +
"INTO @id " +
"VALUES (@Number,@PhoneTypeId) " +
"COMMIT TRAN " +
"SET @ReturnId = (SELECT ReturnColId FROM @id)"
var sqlTransaction = context.Database.SqlQuery(type, insertProcedure, parameters.ToArray());
foreach (var record in sqlTransaction) { } // executes the lazy loading in order to
// populate the out parameter.
Guid newId = new Guid(parameters[parameters.Count - 1].Value.ToString());
OTHER TIPS
Please try the following :
this.context.Database.SqlQuery<string>("p_Insert_Phones @Number = {0}, @PhoneTypeId = {1}", 0, 0);
Where this.context
is the context you want to use ofcourse. The generic type parameter for the SqlQuery
method is the return type of the query result, in your case is a nvarchar which results in a string type.
(Untested, but it's a mockup based on code i used somewhere within one of my projects).