LINQ to SQL Tips 5: Using stored procs that return multiple results
Often I get the following questions about stored procs in LINQ to SQL:
- I have sproc that returns multiple results. How can I use it in LINQ to SQL?
- Can I use a sproc that returns results of different shapes; e.g. Customers and Orders?
- I drag-dropped a sproc returning multiple results on the designer surface. But I don't get a method returning multiple results. What is missing?
Here is the overall answer.
Yes, you can use sprocs returning multiple results of different shapes. Here is an example:
This should be added to your partial class that is derived from DataContext:
[Function(Name="dbo.MultipleResultTypesSequentially")]
[ResultType(typeof(Product))]
[ResultType(typeof(Customer))]
public IMultipleResults MultipleResultTypesSequentially()
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
return ((IMultipleResults)(result.ReturnValue));
}
In consuming code, here is how it can be used
using(IMultipleResults sprocResults = db.MultipleResultTypesSequentially()) {
List<Product> prods = sprocResults.GetResult<Product>().ToList();
List<Customer> custs = sprocResults.GetResult<Customer>().ToList();
…
}
And no, the designer does not support this feature. So you have to add the method in your partial class. SqlMetal does however extract the sproc. The reason for that is an implementation detail: the two use the same code generator but different database schema extractors.
Anyway, with or without SqlMetal, you can use the feature as described above.
Dinesh
I am a program manager in the Visual C# Product Unit of Microsoft. I am currently working on the LINQ project with specific responsibility for DLinq. Previously, I have been in a PM in SQL Server working on ObjectSpaces and DataSet.
In pre-MS life, I have worked for companies ranging from startup to IBM on a wide range of software projects.
Before I started working, I did M.S.E.E. and Ph.D. (CSE) from the University of Notre Dame and B.Tech. E.E. from IIT Bombay, India.