65.9K
CodeProject is changing. Read more.
Home

How to get output parameter values from stored procedure using Entity Framework.

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.63/5 (9 votes)

Oct 14, 2014

CPOL
viewsIcon

70562

This tip gives an explanation with example on how to get output parameter value from stored procedure using Entity Framework in ASP.Net

Introduction

This article helps the developers who works on Entity Framework how to get the output parameter values from stored procedures using Entity Framework in various scenarios like last inserted or updated record ID.

Background

I have already explained how to use stored procedures in Entity Framework in my previous post.

So this is a successor to my previous article, please refer here.

Using the code

1) First of all we need to add an output parameter to a procedure to get the value as mentioned in below example.

Ex :-

CREATE PROCEDURE [dbo].[SP_InsertTestData]
(
      @Value1                VARCHAR(20)
    , @Value2                VARCHAR(MAX)
    , @Value3                VARCHAR(50) = ''
    , @LastInsertedRecordID  INT OUTPUT
)
AS
BEGIN
**********
END

This procedure is created to insert one record to a table.

 

2) Now we need to set the value for this output parameter with last inserted record ID as below :-

--Inside the procedure body
--Below statement goes just after insert statement
SET @LastInsertedRecordID = SCOPE_IDENTITY()

3) Now we need to get this output parameter value in our code as below :-

using (this.objectContext = new TestEntities())
            {
                ObjectParameter objParam = new ObjectParameter("LastInsertedRecordID ", typeof(int));
                var i = this.asterixContext.UpdateFullyPaidRecordStatus(value1, value2, value3, objParam);
                this.objectContext.SaveChanges();
                return Convert.ToInt32(objParam.Value);
            }

 

 

Points of Interest

Hope this will benefit to those who started working with Entity Framework and want to use stored procedures with Entity Framework. Please contact me if any help you need from me.