Sunday, March 1, 2009

LINQ to SQL and multiple result sets in Stored Procedures

When you want to use stored procedure return multiple results you can't depend on auto generated class. You must do it manually, following steps below:
1. Create Entities for returned types:
example: we will create 2 entities ACCOUNT, ACCOUNT_USERS to LINQ to SQL Data Context
2. Create Partail class inherited from LINQ to SQL Data Context and add your method as below:
example for stored procedure will be test.

public partial class DataClasses1DataContext
{
[Function(Name = "dbo.Test")]
[ResultType(typeof(ACCOUNT))]
[ResultType(typeof(ACCOUNT_USER))]
public IMultipleResults Test([Parameter(DbType = "Int")] System.Nullable tmp)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), tmp);
return ((IMultipleResults)(result.ReturnValue));
}
}


3. Now you can use this method as below

DataClasses1DataContext c = new DataClasses1DataContext();
var r = c.Test(null); ;
ACCOUNT a = r.GetResult();
c.Dispose();

No comments: