Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF ExecuteStoredCommand with ReturnValue parameter

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.

like image 817
KDrewiske Avatar asked Dec 09 '11 22:12

KDrewiske


3 Answers

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;
like image 131
Jeff Ogata Avatar answered Oct 18 '22 07:10

Jeff Ogata


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();
like image 38
ProToCooL Avatar answered Oct 18 '22 07:10

ProToCooL


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

like image 26
Diego Mijelshon Avatar answered Oct 18 '22 08:10

Diego Mijelshon