ProgTalk - Your archive for all source code

A Beginners Guide to use LINQ to SQL within ASP.NET in Visual Studio 2008 and CSharp(C#).

ProgTalk » Articles » .NET, C#, ASP.NET, LINQ To SQL, SQL 2005 » A Beginners Guide to use LINQ to SQL within ASP.NET in Visual Studio 2008 and CSharp(C#).
 
Author: Rajib A.
Page Views: 21954
Average Article Rating: rating starrating starrating starrating starhalf star
 


LINQ - What is it?

LINQ is an acronym for LANGUAGE INTEGRATED QUERY.  This feature provides querying capabilties such as select, update, delete which are built into the latest Microsoft frameworks.  This can be applied to a vast range of datasources.  

Wiki definition:  http://en.wikipedia.org/wiki/Language_Integrated_Query

Language Integrated Query (LINQ, pronounced "link") is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages using a syntax reminiscent of SQL.  Many of the concepts that LINQ has introduced were originally tested in Microsoft's C? research project. LINQ was released as a part of .NET Framework 3.5 on November 19, 2007.

LINQ defines a set of query operators that can be used to query, project and filter data in arrays, enumerable classes, XML, relational database, and third party data sources. While it allows any data source to be queried, it requires that the data be encapsulated as objects. So, if the data source does not natively store data as objects, the data must be mapped to the object domain. Queries written using the query operators are executed either by the LINQ query processing engine or, via an extension mechanism, handed over to LINQ providers which either implement a separate query processing engine or translate to a different format to be executed on a separate data store (such as on a database server as SQL queries). The results of a query are returned as a collection of in-memory objects that can be enumerated.


In this tutorial, we will be examining LINQ with SQL, and create a project step by step.

First we will need to create a new website for our project.  Launch Visual Studio 2008 (If you are using the Express Version, this would be Visual Studio Web Developer 2008).  Once the program has launched, go the File menu, and click on New Web Site.





Select the ASP.NET Web Site, Choose your desired programming language, and project title:




The Default.aspx will automatically launch.  Here we will be adding a new item.  Simply right click on the project, and select: "Add New Item"




Choose the "LINQ to SQL Classes", and enter your desired name.  This example uses CategoriesClasses.dbml.
Here is some additional information for "LINQ to SQL" from Microsoft:

LINQ to SQL is a component of .NET Framework version 3.5 that provides a run-time infrastructure for managing  

relational data as objects.


In LINQ to SQL, the data model of a relational database is mapped to an object model expressed in the programming language of the developer. When the application runs,  LINQ to SQL translates into SQL  the language-integrated queries in the object model and sends them to the database for execution. When the database returns the results, LINQ to SQL translates them back to objects that you can work with in your own programming language.





You may get promted to store the information in the App_Code folder.  Click Yes to accept this.





Automatically the CategoriesClasses.dbml will launch.  Here is where we will configure the database table we will work with for this example.  First we need to configure our database.  Click on the database explorer which should come up on the right side of your screen:






Right Click on Data Connections, and click on "Add Connection".  This will let us configure our settings to our desired database.  This will be different based on the type of server you have, and on what machine is resides on.  Make sure you have the database credential information before proceeding:




The wizard to add a new connection will now come up.  
   Select the data source: Microsoft SQL Server (SqlClient)
   Enter the server name: localhost (This may be different on your machine)
   Select "User SQL Server Authentication", and enter the log-on credentials.
   Next select the Northwind Database from the Connect to Database section.
   Make sure to click on the "Test Connection" to make sure that there is an established connection to the db.




Now you should be able to see all the tables of the Northwind database.  Simply drag and drop the Categories table from the Database Explorer, to your CategoriesClasses.dbml designer.
See below for an example:




Now we are ready to have our Default.aspx page communicate with our LINQ To SQL Classes.  First we will drag the GridView control onto our Default.aspx page.  This can be done by simply dragging the GridView control from the Data tab of the Toolbox onto a section of the Default.aspx page.  There should be a div tag by default on your Default.aspx page, in which you can place the GridView.

Once the GridView is in place, drag the LinqDataSource onto the page as well.  The LinqDataSource is going to be used to connect our GridView with our LINQToSQLClasses.
Here is some information about LinqDataSource from Microsoft:  http://msdn.microsoft.com/en-us/library/bb547113.aspx

The LinqDataSource control exposes Language-Integrated Query (LINQ) to Web developers through the ASP.NET data-source control architecture. LINQ provides a unified programming model for querying and updating data from different types of data sources, and extends data capabilities directly into the C# and Visual Basic languages. LINQ simplifies the interaction between object-oriented programming and relational data by applying the principles of object-oriented programming to relational data. For more information about LINQ, see Language-Integrated Query (LINQ).


By using declarative markup, you can create a LinqDataSource control that connects to data from either a database or an in-memory data collection such as an array. In the declarative text, you can write all the conditions that are required to retrieve, filter, order, and group the data. When you retrieve data from a SQL database table, you can also configure a LinqDataSource control to handle updating, inserting, and deleting data. The control does this without requiring you to write the SQL commands to perform these tasks. The LinqDataSource class also provides an event model that enables you to handle customized scenarios.






Next click on the GridView, and expand to view the GridView Tasks.  The "Choose Data Source:" option will appear.  Make sure to select the LinqDataSource we had just added.  The default name should be LinqDataSource1.   Also click on the "Enable Paging", "Enable Sorting", and "Enable Selection" checkboxes.  Notice the change in the GridView columns in the designer.





Next we will configure our LinqDataSource.  Click on the LinqDataSource control, and expand to see the LinqDataSource Tasks.  Here select the "Configure DataSource".




The Configure Data Source for LinqDataSource wizard will launch.  First click on the checkbox which states "Show only DataContext Objects," and select the CategoriesClassesDataContext which we had created earlier.  Click on Next once you have chosen thecontext object.





Here we will leave the Select option to *.  Here is where you would configure the columns you want to display for selection, editing, or updating.  For this tutorial we will keep it simply, and display all the columns for the Categories table. 

Click on the Advanced option on the lower right side, before clicking on Finish.





We want to be able to automatically allow updates to the database when they are edited.   Select the last option which will bring this feature automatically, saving the developer a lot of time from coding.  Imagine how much time this could save you.  Once you have selected this option, click on OK.





You may be prompted to Refresh the fields and keys for GridView1.  Click on Yes for it to automatically perform mappings.





Modify the GridView Tasks once more, but notice that we now have the Enable Editing option.  Select this option as well as the others (Paging, Sorting, Selection).





In order to give a better feel, click on the AutoFormat and choose one of the provided styles.  This tutorial uses the Professional style.




Now we are ready to run the code.  Build the solution, and run the application...  Below you will find a few screen shots of how the page will look and act based on our actions.  You can also sort the data automatically giving it a rich feel.



SCREEN SHOT 1:  Default.aspx page containing GridView with LinqDataSource and LINQ To SQL Classes







SCREEN SHOT 2:  Clicking on Select for an item of the GridView.






SCREEN SHOT 3:  Clicking on Edit for an item of the GridView.






SCREEN  SHOT 4:  Modifying the Description of one of the rows of the GridView






SCREEN SHOT 5:  Click on Update, and watch the results.







This tutorial is a step by step guide to see how powerful framework 3.5 is with LINQ.  You can automatically achieve features such as Edit/Update/Insert/Select/Delete without almost any code.  Look for additional tutorials for more features of LINQ.

 

Notes

Please leave some feedback if you feel there was a mistake, or a different approach.
 

Tags

 

Ratings

Was this article helpful? Don't forget to rate it. Ratings helps community members identify top & useful articles.
Current Rating: rating starrating starrating starrating starhalf star
Rate this article:
(1-Poor, 2-Needs Improvement, 3-Average, 4-Good, 5-Excellent)
 

Feedback

Have a question, suggestion or feedback for this article? Leave your comments below.
Share your feedback:
Need to upload images with your comment. Upload your images here: Image Shack. Remember to copy the url of your uploaded image and insert it into the comment.
You can insert images by clicking on the following icon: insert comment image
(Members Only)
 

Latest Comments

Below are the latest comments from other ProgTalk members.
Posted on:
5/10/2010 9:29:19 PM
Posted by:

hi,
  this tutorial is very helpfull for the people like me.please sended to me more tutorial on yadavnitin11@gmail.com.Can you please send me how to bind gridview in code behind in LINQ and insertion,updation deletion etc.every thing in code behind.

Posted on:
8/25/2009 12:00:00 AM
Posted by:
thanks you very much very good this

<a href="http://www.girhadi.com" title="chat" target=_blank>chat</a>

<a href="http://www.forumdur.tk" title="forum" target=_blank>forum</a>
<a href="http://www.girhadi.com" title="sohbet odalari" target=_blank>sohbet odalari</a>
<a href="http://www.girhadi.com" title="kamerali sohbet" target=_blank>kamerali sohbet</a>
Posted on:
7/29/2009 12:00:00 AM
Posted by:
This was a perfect article!
Just what I needed to get started.

Dear Author! Please do make a part II whenever you get the time.

Sincerely
SamarMir

Posted on:
9/22/2009 4:53:40 PM
Posted by:
<a Href="http://www.trchatodalari.com">Chat Odalari</a>
Posted on:
6/17/2009 12:00:00 AM
Posted by:
TAN
I am sorry to have gone one big round of the loop. After reading the article from http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/7f28b799-2807-4a00-b401-85e425ffa297

I realise my mistake.

Solution = do not have a ''#'' sign in the path where you store the files..

e.g. C:\c#programs\project1\....

Now, all my problem is solved. I hope this information is useful to others.

Posted on:
6/17/2009 12:00:00 AM
Posted by:

Hey Tan,

Wow, I would have never figured that one out. 
Thanks for posting the tip. 
I think this will help resolve this issue for so many people. 

Posted on:
6/16/2009 12:00:00 AM
Posted by:
The article is really helpful. Thanks a lot.
Posted on:
6/16/2009 12:00:00 AM
Posted by:
TAN,
after you add the GridView and LinqDataSource (after you configure the database connection), save your project and you will see your table in the wizard. This is how it worked for me.

The article is very helpful. Thanks a lot.
Posted on:
6/16/2009 12:00:00 AM
Posted by:
TAN
still, it does not work, I find it strange. What other suggestions?
Posted on:
6/16/2009 12:00:00 AM
Posted by:
TAN
I go to the Properties of LinqDataSource1, and manually type in CategoriesClassesDataContext in the ContextTypeName field. Then I click that Smart Tag of LinqDataSource1, Configure Data Source. On the screen of Choose a Context Object, I checked the checkbox for Show only DataContext objects. Now, CategoriesClassesDataContext is being displayed in that listbox under Choose your context object:
When I click the Next button,
Microsoft Visual Studio error says:
The type ''CategoriesClassesDataContext'' could not be loaded. If the type is located in the App_Code folder, please check that it compiles. If the type is located in a compiled assembly, please check that the assembly is referenced by the project.
Posted on:
11/18/2009 3:24:34 PM
Posted by:
I too get the same error.  any one ?
Posted on:
6/15/2009 12:00:00 AM
Posted by:
TAN
No, it does not work.
I am using Windows Authentication, instead of SQL Server Authentication. I suppose it does not matter, as my Test Connection passed.
Posted on:
6/15/2009 12:00:00 AM
Posted by:
TAN
No, it does not work.
I am using Windows Authentication, instead of SQL Server Authentication. I suppose it does not matter, as my Test Connection passed.
Posted on:
6/14/2009 12:00:00 AM
Posted by:
TAN
I have the same problem as Richard,
I''''ve tried several times, following carefuly all the steps, but I''''m still stauck at "Configure Data Selection." Nothing appears, even after Build and Rebuild. Could anyone help? thanks 
Posted on:
6/14/2009 12:00:00 AM
Posted by:
After you pointed to your database, setup a connection, and dragged your tables build your project.  Then on the page you will add the datasource go to the code behind.  If you are using csharp, at the top write:
using System.Linq;
Then try to see if you can access any of the table methods.  So if you named your dbml file DBML, it should come as DBML.Tbl_YourTables.  If this is not happening, it isn't synching with your db.  If it is, then you should be able to use the linq datasource.  Let me know if this helps.
Posted on:
5/19/2009 12:00:00 AM
Posted by:
this is the best article. very simple. Keep it up
Posted on:
3/18/2009 12:00:00 AM
Posted by:

Hi,

I''ve tried several times, following carefuly all the steps, but I''m still stauck at "Configure Data Selection." Nothing appears. 

Thanks.  
Posted on:
6/17/2009 12:00:00 AM
Posted by:
check out the post by Tan.  This should help your problem. 
Posted on:
3/18/2009 12:00:00 AM
Posted by:

Hi,

I''ve tried several times, following carefuly all the steps, but I''m still stauck at "Configure Data Selection." Nothing appears. 

Thanks.  
Posted on:
5/9/2009 12:00:00 AM
Posted by:
I am not sure why you are getting stuck there.  After dragging the tables onto designer, do a build.  Then see if you get the proper configure data selection option.
Posted on:
1/17/2009 12:00:00 AM
Posted by:
nice thanks
Posted on:
12/15/2008 12:00:00 AM
Posted by:
Good Article..Very Useful for Beginners


Dilip
Web Developer
Posted on:
10/15/2008 12:00:00 AM
Posted by:
This article is good  i''d prefer to study how to use linq by coding not wizard

and also i want to know if its possible to use procedures instead of tables in linq
Posted on:
6/27/2009 12:00:00 AM
Posted by:
Posted on:
8/26/2008 12:00:00 AM
Posted by:
Thanks for sharing that aritcal. This is very good for the begineer to fisrt understand what can do linq?
Could you tell post the artical where we can configure or use linq throuth Coding not with Wizard
Posted on:
8/24/2008 12:00:00 AM
Posted by:
I am interested in how you build a Linq datasource that uses products and categories, where the focus (the updateable table) is products but you want to use the category info via the relatiojship to category. I cannot seem to get that to work.

In addition, I cannot get the "enable editing" checkbox in the simple example.
Posted on:
8/20/2008 12:00:00 AM
Posted by:
This is perfectly what anybody need in start.

I would like to get more tutorials from you.

If you have please let me know my mail id is piyushghodasara@hotmail.com

I appreciate your work.
Posted on:
8/14/2008 12:00:00 AM
Posted by:

I can''t configure the datasource, the Configure Data Source screen doesn''t populate.

Posted on:
8/14/2008 12:00:00 AM
Posted by:
You have to set your data connection.  Once you do that you have to drag the table which you want to work on.  I think its like the 6th or 7th step.  Once you do this, then you will be able to configure the data source.
Posted on:
5/19/2008 12:00:00 AM
Posted by:
Perfect :)