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.
Open Visual Studio 2008 and select a ASP.Net Web Application. Make sure you select .Net Framework 3.5
Add a GridView to the to a web form (and add a style to the Grid using Auto Format)
Add a Linq to SQL Class.
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.
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.