January 23, 2021
Hot Topics:

Language Integrated Query (LINQ) to SQL

  • By Mark Strawmyer
  • Send Email »
  • More Articles »

Calling Stored Procedures

The previous retrieve, create, update, and delete operations involved dynamically generated SQL statements. It is also possible to call stored procedures in place of dynamically generated SQL. The sample code below demonstrates how to call stored procedures. The Northwind database has a stored procedure called "Ten Most Expensive Products" we will use for this example. Once again using the Server Explorer navigate to the Stored Procedures in the tree view and drag the stored procedure to the design surface. You'll want to right click on the design surface and select "Show Methods Pane" if it isn't already available. You should now see a method, Ten_Most_Expensive_Products(), that has been created and we'll use in our next code example to get the list of top products and display the prices to the console.
  using (NorthwindDataClassesDataContext context =   new NorthwindDataClassesDataContext())  {    // Use the ten most expensive products stored procedure    var results = from products in context.Ten_Most_Expensive_Products()      select products;      foreach (var product in results)    {  Console.WriteLine("Product price is {0}", product.UnitPrice);    }      // Pause to see the output    Console.ReadLine();

The stored procedure example above is pretty straight forward. You can create your own stored procedures, including those that have input parameters, and use them in a similar manner.


You have now seen LINQ to SQL and the simplicity that it can bring to working with SQL Server based databases. We have examined the object model involved, retrieving and altering data through dynamically generated SQL statements, and calling stored procedures.

Future Columns

The topic of the next column is likely to be LINQ to Entities, which is another form of LINQ for accessing relational data. If you have something else in particular that you would like to see explained here please e-mail me.

About the Author

Mark Strawmyer is a Senior Architect of .NET applications for large and mid-size organizations. Mark is a technology leader with Crowe Horwath LLP in Indianapolis, Indiana. He specializes in architecture, design and development of Microsoft-based solutions. Mark was again honored to be named a Microsoft MVP for application development with C#. You can reach Mark at mark.strawmyer@crowehorwath.com.

Page 3 of 3

This article was originally published on April 28, 2009

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date