LINQ to SQL Classes

LINQ to SQL classes that are mapped to database tables and views are called entity classes. The entity class maps to a record, whereas the individual properties of an entity class map to the individual columns that make up a record. Create entity classes that are based on database tables or views by dragging tables or views from Server Explorer/Database Explorer onto the Object Relational Designer (O/R Designer).



Demo :

1 - Open Visual Studio 2008 and create a new ASP.NET Web Application.
     File --> New --> Web Site --> Visual C# --> ASP.NET Web Application --> Give name of the  application (for Ex- LinqtoSqlClasses).

2 - Right-click on the "App_Data" folder and select Add --> New Item.

3 - Once the Add New Item windows opens select "LINQ to Sql Classes" and name it "Northwind.dbml" as follows:

4 - Now connect your Database in server explorer and drag and drop the tables to Northwind.dbml file. It will automatically converted into a class. See the image below.

   a) Click on server explorer.


    b) Click on connect to database.


      c) Enter credentials to connect to the database.

                
                     Click on OK button.

        d) Drag your table from server explorer and drop it to the dbml file.



               Press Ctrl+S to save your work.

    5 - Open your default.aspx page. Drag and drop grid view control from tool box menu on to the page.
   
    6 - Write the below code on the page load to fetch data from database.

           protected void Page_Load(object sender, EventArgs e)
          {
               if (!IsPostBack)
              {
                     Bind();
               }
          }

          private void Bind()
         {
               NorthwindDataContext db = new NorthwindDataContext();

               var category = from c in db.Categories
                                      select c;

               grdCategory.DataSource = category;
               grdCategory.DataBind();
         }
            
    7 - Save and run the application. You will get your required output.

          

Comments