Welcome to MSDN Blogs Sign in | Join | Help

DDITDev

A crack team of devs in the Developer Division. ASP.NET, SQL, C#, development practices.
LINQ to SQL and multiple result sets in Stored Procedures

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.

clip_image001

In my LINQ to SQL Data Context, I have the following tables.

clip_image002

As well as the stored procedure definition.

clip_image003

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.

clip_image004

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.

clip_image005

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!

image

I hope this helps!

Jason

Posted: Tuesday, May 06, 2008 2:34 PM by dditweb
Filed under: , , ,

Comments

Him said:

Jason, what if we want to return multiple resultsets that are not typed? like anonymous types?

like for example:

select pr.Title, pr.Description from products

select o.orderid, u.userid from orders o

inner join users u on o.userid = u.userid

# May 6, 2008 6:48 PM

Leakybagel said:

If you get errors like 'Procedure expects parameter <@Name>, which was not supplied:

Take a look at the stored procedure code created in the Designer.cs file, and copy the parameter list and attributes that match them to the SP params: [Parameter(Name="CustomerID", DbType="Int")]

When passing multiple parameters to ExecuteMethodCall, you don't need to create an object array, just list each parameter.

Can you skip over one of the results, or is each result set returned in order?

# July 21, 2009 11:02 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

  
Enter Code Here: Required

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker