In this post I'm going to demonstrate how you would return and consume multiple result sets from a stored procedure in LINQ to SQL.
Imagine you have a stored procedure like this one below. Very simple – it’s just returns all customers and all orders.
In my LINQ to SQL Data Context, I have the following tables.
As well as the stored procedure definition.
Simple enough so far!
The first thing we need to do is create a partial class and define a new method returning type ‘IMultipleResults’. I’ve defined the one below to accept one parameter, which is a customerId.
You’ll notice that there’s a few attributes you need to add.
1. Function – this is the name of the stored procedure that will be called. It’s the same one we defined in our data context above. Note: the actual stored procedure name is irrelevant - it must be the name you have given the stored procedure on the data context (which will be the same 99% of the time I’d imagine.)
2. ResultType – This is the mapping that basically says “Make the first result type of ‘Customer’ and the second result type of ‘Order’”.
Once we’ve defined this method, we can go ahead and consume it from our UI and/or OM as shown below.
As shown above, you call the method you defined, passing in a customer id in this case, which returns you a type of IMultipleResults. From there it’s just a case of calling the ‘GetResult’ method making sure to pass in the type of the object you want.
The results are shown below!
I hope this helps!