It’s not very often, but there are times when a stored procedure just works a little better than LINQ. Complexity for developers can be decreased while performance can be dramatically increased for users. In those very rare cases, it may make sense to return more than one result set from a stored procedure. This post will show you how to utilize Entity Framework 6 to execute a stored procedure and materialize multiple result sets. This post specifically focuses on objects not found in your DbContext.
Returning multiple result sets is a feature of SqlClient that Entity Framework can take advantage of. It can pipeline multiple results over the same connection to reduce the number of round trips to retrieve data. This can lead to a significant performance increase that users will thank you for.
The Data
In this example we will have two tables: Cats and Dogs. You can find the script below.
When we execute our stored procedure, we get the following results.
Returning Multiple Results Sets (The Messy Way)
The code borrows from an Entity Framework example found on MSDN. The difference between my code and the example on MSDN, is the POCOs don’t necessarily have to be in the DbContext.
Note that the classes of Dog
and Cat
are not in the DbContext. This means your stored procedure results are not tied directly to your Entity Framework models. When we execute the following code we get the result we are looking for.
Returning Multiple Results Sets (The Reuseable Way)
There is clearly a pattern here.
- Execute the command
- Map to what we think the result looks like
- Return multiple enumerables
Let’s see if we can make a helper class that can encapsulate that complexity. What I’d like to be able to do is write some code like this.
That’s what I’ve done with the code below.
When we execute the new helper, we get the following results.
Note that all the results are there, but they are coming back as IEnumerable
. You can utilize the Cast
method in LINQ to strong type the enumerable.
There you have it! Use Entity Framework 6 to execute a stored procedure with multiple result sets even if your results are not in your DbContext.