Home.NET Beginning LINQ to SQL Using Visual Studio ...
Beginning LINQ to SQL Using Visual Studio 2008
This is an introductory article which focuses on fetching and updating databases using the DataContext object in "LINQ to SQL." By reading this article, you will learn how to work with "LINQ to SQL" manually, without using a designer and with great simplicity. It should serve to give a solid foundation to both VB and C# programmers.
I will not be including great theories of LINQ or related technologies in this article; Microsoft already features great content on those topics on its MSDN. If you are absolutely new to LINQ, I request that you go through the information you'll find at this link first:
The entire source code for this article is available in the form of a free downloadable zip file. The solution was developed using Microsoft Visual Studio 2008 Team Edition on Microsoft Windows Server 2003 Standard Edition with Microsoft SQL Server 2005 Developer Edition. I didn't really test it in any other environment. I request that you post in the discussion area if you have any problems in execution.
Developing a simple "LINQ to SQL" application (without LINQ designer): creating the project
It is always easier to work with wizards and designers rather than coding manually. But when it comes to customizing the auto-generated code, we should have a fair understanding of generated code and its related pieces.
We can generate lots of code automatically using Visual Studio designers (like DataSet Designer, LINQ to SQL Designer, etc.). As this is the most fundamental article on "LINQ to SQL," I would like to introduce the manual way of coding first rather than using "LINQ to SQL Designer" and complicating things. This is only to give you a better understanding of "LINQ to SQL" from the point of view of grasping the basics. My upcoming articles gradually focus on working with LINQ to SQL Designer.
To make this article simple, I created two tables, "emp" and "dept" as follows:
The following are the steps for creating an ASP.NET 3.5 application with "LINQ to SQL" support:
Open Visual Studio 2008
Go to File || New || Project
In the "New Project" dialog, make sure ".NET Framework 3.5" is selected. In the "Project Type," select either "Visual Basic || Web" or "Visual C# || Web."
Select "ASP.NET Web Application" in the templates, provide the name of the application (Fig 3) and finally hit the OK button.
DataContext db = new DataContext(new System.Data.SqlClient.SqlConnection("Data Source=.sql2k5;initial catalog=sample;user id=sa; password=eXpress2005"));
Once the UI is designed as discussed in the previous section, we need to code for the button clicks (in code-behind) for all add, update, delete, search and refresh buttons.
The following is the source code in VB.NET 2008:
Imports System.Data.Linq
Partial Public Class CRUDSample
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.lblMsg.Text = ""
End Sub
Protected Sub btnSelectStar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSelectStar.Click
Dim db As New DataContext(New System.Data.SqlClient.SqlConnection("data source=.sql2k5;initial catalog=Sample;user id=sa;Password=eXpress2005"))
Dim tblEmps As Table(Of Emp) = db.GetTable(Of Emp)()
Me.GridView1.DataSource = tblEmps
Me.GridView1.DataBind()
End Sub
Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSearch.Click
Try
'getting table
Dim db As New DataContext(New System.Data.SqlClient.SqlConnection("data source=.sql2k5;initial catalog=Sample;user id=sa;Password=eXpress2005"))
Dim tblEmps As Table(Of Emp) = db.GetTable(Of Emp)()
'getting an exiting row
Dim objEmp As Emp = tblEmps.SingleOrDefault(Function(p) p.empno = Me.txtEmpno.Text)
If objEmp IsNot Nothing Then
Me.txtEname.Text = objEmp.ename
Me.txtSal.Text = objEmp.Sal
Me.txtDeptno.Text = objEmp.deptno
Else
Me.lblMsg.Text = "Employee not found"
End If
Catch ex As Exception
Me.lblMsg.Text = ex.Message
End Try
End Sub
Protected Sub btnInsert_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnInsert.Click
Try
'getting table
Dim db As New DataContext(New System.Data.SqlClient.SqlConnection("data source=.sql2k5;initial catalog=Sample;user id=sa;Password=eXpress2005"))
Dim tblEmps As Table(Of Emp) = db.GetTable(Of Emp)()
'adding a new row
Dim rEmp As Emp = New Emp With {.empno = Me.txtEmpno.Text, .ename = Me.txtEname.Text, .Sal = Me.txtSal.Text, .deptno = Me.txtDeptno.Text}
tblEmps.InsertOnSubmit(rEmp)
'saving rows added
db.SubmitChanges()
Me.lblMsg.Text = "Added Successfully"
Catch ex As Exception
Me.lblMsg.Text = ex.Message
End Try
End Sub
Private Sub btnUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Try
'getting table
Dim db As New DataContext(New System.Data.SqlClient.SqlConnection("data source=.sql2k5;initial catalog=Sample;user id=sa;Password=eXpress2005"))
Dim tblEmps As Table(Of Emp) = db.GetTable(Of Emp)()
'getting an exiting row
Dim objEmp As Emp = tblEmps.SingleOrDefault(Function(p) p.empno = Me.txtEmpno.Text)
If objEmp IsNot Nothing Then
'modifying the row
objEmp.ename = Me.txtEname.Text
objEmp.Sal = Me.txtSal.Text
objEmp.deptno = Me.txtDeptno.Text
'saving rows added
db.SubmitChanges()
Me.lblMsg.Text = "Updated Successfully"
Else
Me.lblMsg.Text = "Employee not found"
End If
Catch ex As Exception
Me.lblMsg.Text = ex.Message
End Try
End Sub
Private Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
Try
'getting table
Dim db As New DataContext(New System.Data.SqlClient.SqlConnection("data source=.sql2k5;initial catalog=Sample;user id=sa;Password=eXpress2005"))
Dim tblEmps As Table(Of Emp) = db.GetTable(Of Emp)()
'getting an exiting row
Dim objEmp As Emp = tblEmps.SingleOrDefault(Function(p) p.empno = Me.txtEmpno.Text)
If objEmp IsNot Nothing Then
'delete the row
tblEmps.DeleteOnSubmit(objEmp)
'saving rows deleted
db.SubmitChanges()
Me.lblMsg.Text = "Deleted Successfully"
Else
Me.lblMsg.Text = "Employee not found"
End If
Catch ex As Exception
Me.lblMsg.Text = ex.Message
End Try
End Sub
End Class
Once executed, it should give the output as follows (Fig 06):
DataContext db = new DataContext(new System.Data.SqlClient.SqlConnection("data source=.sql2k5;initial catalog=Sample;user id=sa;Password=eXpress2005"));
DataContext db = new DataContext(new System.Data.SqlClient.SqlConnection("data source=.sql2k5;initial catalog=Sample;user id=sa;Password=eXpress2005"));
DataContext db = new DataContext(new System.Data.SqlClient.SqlConnection("data source=.sql2k5;initial catalog=Sample;user id=sa;Password=eXpress2005"));
//getting table
Table<Emp> tblEmps = db.GetTable<Emp>();
//adding a new row
Emp rEmp = new Emp {empno = Int32.Parse(this.txtEmpno.Text), ename = this.txtEname.Text, sal = Double.Parse(this.txtSal.Text), deptno = Int32.Parse(this.txtDeptno.Text)};
DataContext db = new DataContext(new System.Data.SqlClient.SqlConnection("data source=.sql2k5;initial catalog=Sample;user id=sa;Password=eXpress2005"));
DataContext db = new DataContext(new System.Data.SqlClient.SqlConnection("data source=.sql2k5;initial catalog=Sample;user id=sa;Password=eXpress2005"));
My upcoming articles will focus further in-depth on "LINQ to SQL" (including designers). I hope you enjoyed this article and any suggestions, bugs, errors, enhancements etc. are highly appreciated at http://jagchat.spaces.live.com