Wednesday, November 18, 2009

Get data from StoredProc returning Table using Linq2Sql

I was using the Linq to Sql to execute a stored procedure, returning results by using a temporary table.
When I dropped the procedure on to the .dbml file, it generated a function with the return value typed as Integer.

The Stored Procedure looks like this:
--------------------------------------------
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

CREATE procedure [dbo].[test_proc]
as
begin

create table #temp_table
(
col1 varchar(255),
col2 varchar(255)
)

insert into #temp_table (col1, col2) values ('ram', 'shyam')
select * from #temp_table
end
go

My solution to this problem was:
---------------------------------
I created a partial class as under. You have to use the namespace System.Data.Linq.Mapping for the Table and Column tags.

[Table]
public partial class test_proc_Result
{
public test_proc_Result() { }

[Column]
public string col1;
[Column]
public string col2;
}

and then you have to modify the Function in the DBML's .designer.cs file and you r done.

[Function(Name="dbo.test_proc")]
public IEnumerable<'test_proc_Result'> test_proc()
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
return result.ReturnValue as IEnumerable<'test_proc_Result'>;
}

Calling function :
-------------------
List<'test_proc_Result'> result = db.test_proc().ToList();

You would find the values passed from the Store_proc in the result variable.
In case you are returning any scalar value such as BIT from the stored procedure.
Then the function should be changed like this:

[Function(Name="dbo.test_proc")]
public ISingleResult<'test_proc_Result'> test_proc()
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
return result.ReturnValue as ISingleResult<'test_proc_Result'>;
}


Note: Please remove all " ' " from the code