LINQ the Language Integrated Query.
OK… So what’s this so hyped word carry with it. Actually it’s another way of querying data sources within .Net languages.
LINQ libraries came with .NET Framework 3.5, and Visual Studio 2008 IDE can be used to take the maximum out of it. Languages that facilitate LINQ provide type safety as well as compile time checking of queries. VS 2008 provides debugging of LINQ queries, intellisense and refactoring too.
Microsoft has provided us different APIs that provide a gateway to underlying data sources, such as
LINQ to SQL
LINQ to XML
LINQ to DataSets
LINQ to Objects
LINQ to Entities (Still in beta)
Today I’m planning to show a very simple LINQ to SQL query step by step. It’s more like how to write a simple SELECT statement inline C#. OK…Fasten your seat belts.
Step 1
Open Visual Studio 2008 and select a ASP.Net Web Application. Make sure you select .Net Framework 3.5
Step 2
Add a GridView to the to a web form (and add a style to the Grid using Auto Format)
Step 3
Add a Linq to SQL Class.
Step 4
Create a connection to a Database (optional: using Server Explorer). It'll be easy if you add the connection string to the Web.config file.
Step 5
Drag the tables you want, from Server Explorer to the design surface of the Linq to SQL class. Here in this scenario I'll add the Store and the SalesPerson tables. Wow... check out the association created automatically.
Have a look at the properties window. You see the connection which has been accessed from the Web.Config.
OK... Now we have come to the coding part. First create a DataContext of the LINQ to SQL class you have already created. In this case it's AdventureWorksDataContext. Then create a var type variable and assign it to the link query. Yes... the query is not very user friendly until you get used to it. Whats this "s"? It's the structure of the db.Stores. And you can use any letter/word to represent "s". Finally, set the result to the DataSource of the GridView and call the DataBind() method of the GridView.