I have a stored procedure that has three parameters and I've been trying to use the following to return the results:
context.Database.SqlQuery<myEntityType>("mySpName", param1, param2, param3);
At first I tried using SqlParameter
objects as the params but this didn't work and threw a SqlException
with the following message:
Procedure or function 'mySpName' expects parameter '@param1', which was not supplied.
So my question is how you can use this method with a stored procedure that expects parameters?
Thanks.
I had the same error message when I was working with calling a stored procedure that takes two input parameters and returns 3 values using SELECT statement and I solved the issue like below in EF Code First Approach
UPDATE: It looks like with SQL SERVER 2005 missing EXEC keyword is creating problem. So to allow it to work with all SQL SERVER versions I updated my answer and added EXEC in below line
I use this method:
I like it because I just drop in Guids and Datetimes and SqlQuery performs all the formatting for me.
Most answers are brittle because they rely on the order of the SP's parameters. Better to name the Stored Proc's params and give parameterized values to those.
In order to use Named params when calling your SP, without worrying about the order of parameters
Using SQL Server named parameters with ExecuteStoreQuery and ExecuteStoreCommand
Describes the best approach. Better than Dan Mork's answer here.
E.g.:
or
or
or
Also, you can use the "sql" parameter as a format specifier:
@Tom Halladay's answer is correct with the mention that you shopuld also check for null values and send DbNullable if params are null as you would get an exception like
The parameterized query '...' expects the parameter '@parameterName', which was not supplied.
Something like this helped me
(credit for the method goes to https://stackoverflow.com/users/284240/tim-schmelter)
Then use it like:
or another solution, more simple, but not generic would be: