Linq to Sql

          Hi, this is Satalaj. In this article we will see how to query any database using DatabaseContext and Linq query syntax. we will use VS 2008.

We will follow below steps

 1. Add Linq to Sql classes
 2. Open connection using Server Explorer to the Database on that server (Note you can open connection to any database on any server)
 3. Drag and drop table into Linq to Sql interface (.dbml) file.
 4. open .aspx page file Add Gridview control in it and on page load event of that page we will query the DatabaseContex using Query

Steps

1. Add Linq to Sql classes into your web project as shown in Fig1.


Fig1.

2. Open connection using Server Explorer to the Database on that server (Note you can open connection to any database on any server)



Fig2.

As show in fig2. first open connection with DB server using Server explorer.
Drag and drop the table from Server explorer to the .Dbml file Fig.2.
Now We are ready to query .dbml Database context using Linq syntex.
3. Drag and drop table into Linq to Sql interface (.dbml) file. Fig2.

Fig3.

Fig 3. shows AdventureWorksDatabaseContext
**Note: AdventureWorksDatabaseContext is autogenerated class at the time of adding Linq to Sql classes in web project Fig.1

 4. open .aspx page file Add Gridview control in it and on page load event of that page we will query the DatabaseContex using Query



below is the code used in side .aspx page code behind file

using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

public partial class Linq_To_SQL : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

AdventureWorksDataContext advDBc = new AdventureWorksDataContext();

var query = from productEntities in advDBc.Products

select productEntities;

GridView1.DataSource = query;

GridView1.DataBind();

 

}

}

 For more info refer http://weblogs.asp.net/scottgu/archive/2007/01/28/video-using-linq-with-asp-net-in-vs-orcas-part-1.aspx

Thanks Satalaj.

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.