Before we can start using LINQ to call stored procedure, first we need to create new connection and map it on LINQ To SQL designer as explained on my previous article: What is LINQ to SQL? An Introduction
If you already finished mapping the stored procedure on LINQ to SQL designer, lets move forward to the actual code. On the example below, I used the stored procedure "GetProductsByCategory" which accepts category as parameter.
using (NorthwindDataContext datacontext = new NorthwindDataContext())
{
//retrieve all product that are beverage using stored procedure "GetProductsByCategory"
var products = datacontext.GetProductsByCategory("Beverages");
//display all retrieved products from stored procedure
foreach(Product p in products)
{
Console.WriteLine(p.ProductName);
}
}
Translation in VB.NET
Dim datacontext As New NorthwindDataContext()
'retrieve all product that are beverage using stored procedure "GetProductsByCategory"
Dim products = datacontext.GetProductsByCategory("Beverages");
'display all retrieved products from stored procedure
For Each p as Product In products
Console.WriteLine(p.ProductName)
Next
As you can see, retrieving records through stored procedure using LINQ to SQL is relatively easy. Try it now on your application.
For more LINQ coding tips, subscribe now
0 comments:
Post a Comment