Thursday, May 24, 2012

LINQ to SQL - call stored procedure with parameters


LINQ to SQL - call stored procedure with parameters

Before writing a LINQ to SQL query, we first need to create a DataContext using the LINQ to SQL Classes template, to know more on how to create the DataContext refer to the post LINQ to SQL Sample


Once the DataContext is in place we can go ahead and use it to process data from the mapped database.

Assume that we have the following StoredProcedure [InsertDepartment], in the database
ALTER PROCEDURE [dbo].[InsertDepartment]
      @DepartmentName varchar(50)
AS
BEGIN
      INSERT INTO Department (Name) Values (@DepartmentName);
END

Before using LINQ-to-SQL to call the StoredProcedure we need to add the StoredProcedure to the right side panel of the DataContext (.dbml) file.

Open the server Explorer and drag the procedure to the right side panel of the .dbml file, your panel should look as follows.



Once this is done we are ready to call the StoredProcedure from the code, the code is as follows.

EmployeeClassesDataContext dbContext = new EmployeeClassesDataContext();
dbContext.InsertDepartment("IT Support");

That’s it, we have called a Stored procedure with a parameter using LINQ-to-SQL.

Search Flipkart Products:
Flipkart.com

1 comment:

avik ghosh said...

thanks....