Stored Procedure returning entities and output parameter

If you have a stored procedure that returns a collection of entities and also an output parameter, you must iterate through the resultset before the output value is available on the client. Accessing the output parameter value before looping through the result would give you null value. Let’s walk through an example to see how we can correctly access an output parameter value from a stored procedure.

1.  Create Movies table with Title, Rating and Year columns as shown below.

image

2. Create a stored procedure that returns movies filtered by year. The stored procedure also returns average rating for those movies as an output parameter. Code below shows the stored procedure

image

3. Import the table and the stored procedure into an ADO.net Entity Data Model.

4. Open up the model browser by right clicking any where on the model surface and selecting model browser. Find the GetMovies stored procedure in the store section of the model browser. Right click the store procedure and select Add Function Import. Choose the return type to be Movie entity and click Ok. This creates a method on our derived object context that will allow us to call our stored procedure.

Now we are all ready to call our GetMovies method. The GetMovies method takes two parameters. First parameter is the year which is used in our stored procedure filter. Its of nullable integer type. Second parameter is an ObjectParameter which we will use to retrieve the averagerating output value from the stored procedure. Code below returns movies and average rating for those movies.

image

On the above code, we create an object parameter with the name of averagerating of decimal type. The value for this parameter is automatically set by the runtime once you have finished iterating through the resultset.

Figure below shows the output from the above code.

image

3 Comments

  • Thanks So much
    this was my problem
    thanks

  • Thanks for sharing.
    Seems to me that linq is finding the balance between less coding time and perfomance downside and more code time (with stored procedures) and better performance.

  • Many thanks, specially for the comment "must iterate through the movies before i can access averagerating output parameter"

    I saw many such solutions, but not a single one said that; and I had no idea why the output parameter was not being populated.

    You saved my day.

Comments have been disabled for this content.