I'm creating a new application which needs to interface with legacy code :(.
The stored procedure I'm attempting to call uses RETURN for its result. My attempts to execute and consume the return value result in the exception:
InvalidOperationException: When executing a command, parameters must be exclusively database parameters or values.
Changing the stored proc to return the value another way isn't desired, since it either requires updating the legacy app or maintaining a nearly duplicate stored proc.
The legacy stored proc synopsis:
DECLARE @MyID INT
INSERT INTO MyTable ...
SELECT @MyID = IDENTITY()
RETURN @MyID
My Entity Framework / DbContext work, which yields the above InvalidOperationException.
SqlParameter parm = new SqlParameter() {
ParameterName = "@MyID",
Direction = System.Data.ParameterDirection.ReturnValue
};
DbContext.Database.ExecuteSqlCommand("EXEC dbo.MyProc", parm);
Looking for any and all solutions which don't require the stored proc to be modified.
You can capture the return value of the stored procedure into an output parameter instead:
SqlParameter parm = new SqlParameter() {
ParameterName = "@MyID",
SqlDbType = SqlDbType.Int,
Direction = System.Data.ParameterDirection.Output
};
Database.ExecuteSqlCommand("exec @MyId = dbo.MyProc", parm);
int id = (int)parm.Value;
I know it's a bit late, but this works for me:
var param = new SqlParameter("@Parameter1", txtBoxORsmth.text);
someVariable = ctx.Database.SqlQuery<int>("EXEC dbo.MyProc", param).First();
You don't have to use ExecuteSqlCommand
.
You can just get the underlying connection from DbContext.Database.Connection
and use raw ADO.NET (CreateCommand()
, ExecuteNonQuery()
, ...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With