24

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.

9 Answers 9

37

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;
1
  • Only answer that doesn't try fobbing you off with SqlQuery instead of a solution for ExecuteSqlCommand. This is what was tripping me up, you would think that @MyId should be ParameterDirection.ReturnValue but for some reason that defies all understanding, it needs to be ParameterDirection.Output.
    – user692942
    Nov 7, 2019 at 10:22
2

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();
0
1

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(), ...)

0
0

The error message

InvalidOperationException: When executing a command, parameters must be exclusively database parameters or values.

means that you're not providing the right type (or something else which isn't shown in your code snippet) in the params list of SQLParameters.

In my case I had forgotten to remove a MergeOption because I changed the way the SQL command was executed.

0

This extension method will do all the dirty work for you now. See fuller description on SO here.

0

This will return the int from a stored proc using DBContext:

var newId = DbContext.Database.SqlQuery<int>("EXEC dbo.MyProc @MyID = {0}", parm).First();
3
  • 3
    This is a terrible suggestion. This code is vulnerable to SQL injection attacks. Very rarely is this kind of statement construction and execution a good idea. Always try to use parameterized queries. Jun 10, 2015 at 1:22
  • 6
    @NathanAldenSr - the SqlQuery method automatically converts the parameters that you supply into DbParameters. This is a parameterised query - it has to be in order to call a stored procedure that takes parameters. msdn.microsoft.com/en-us/library/…
    – Colin
    Feb 20, 2017 at 16:11
  • @Colin Ah, my fault for not better understanding the method then. Feb 21, 2017 at 14:41
-1

Create table for With parameter example for testing or change the second sql query according to yours.

CREATE TABLE [dbo].[Test](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NOT NULL,
 CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

//========================= =================================//

        public void Test()
        {
                  using (var db = new DbContext())
                  {
                      string sql = "dbo.MyProc";  //With Out Parameter

                  int id1 = (int)db.Database.SqlQuery<decimal>(sql).FirstOrDefault();
                  db.SaveChanges();

                  //Or

                  sql = "INSERT Test(Name) values({0}) SELECT SCOPE_IDENTITY();";  //With Parameter
                  int id2 = (int)db.Database.SqlQuery<decimal>(sql, new object[] { "Thulasi Ram.S" }).FirstOrDefault();
                  db.SaveChanges();
              }
        }
0
-2

I tried the ways above, but only this way works out for me(Must have the 'ToList()' function):

 SqlParameter res = new SqlParameter()
        {
            ParameterName = "Count",
            Value=1,
            Direction = System.Data.ParameterDirection.Output
        };
db.Database.SqlQuery<object>(
         "[dbo].[GetWorkerCountBySearchConditions] @Count ,
         res
         ).ToList();
        return Convert.ToInt32(res.Value);
-4

I'm sure this isn't the only valid answer, but one that I ultimately used and has been working successfully.

The key seemed to be naming the ReturnValue parameter RetVal.

SqlParameter id = create.Parameters.Add("RetVal", System.Data.SqlDbType.Int);
id.Direction = System.Data.ParameterDirection.ReturnValue;

putting it all together:

SqlCommand proc = new SqlCommand("dbo.MyProc", new SqlConnection(<connection string>));
proc.CommandType = System.Data.CommandType.StoredProcedure;

SqlParameter id = create.Parameters.Add("RetVal", System.Data.SqlDbType.Int);
id.Direction = System.Data.ParameterDirection.ReturnValue;

proc.ExecuteNonQuery();

int newId = Convert.ToInt32(id.Value);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.