Introducing LINQ to SQL Designer using Visual Studio 2008

This is an introductory article that focuses on designing LINQ to SQL objects using the LINQ to SQL Designer in Visual Studio 2008. Apart from designing, we will concentrate on fetching and updating databases using the model created with Designer.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 20
April 07, 2008
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

If you are a bit new to programming LINQ, please consider reading my previous article titled "Beginning 'LINQ to SQL' using Visual Studio 2008."

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.

Creating a simple "LINQ to SQL" application: creating the project

In my previous article, we focused on "LINQ to SQL" development without working with a designer. "LINQ to SQL" designer is a great choice and has lots of features that we can take advantage of. We can take full advantage of it, if we know what it is doing internally.

Before going into complete internal details, let us start by creating a 'LINQ to SQL' application using a designer.

To make this article simple, I created two tables, "emp" and "dept," as follows:


The following are the steps used to create an ASP.NET 3.5 application with a "LINQ to SQL" designer:

  • 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 OK.


Creating a simple "LINQ to SQL" application: using "LINQ to SQL Designer"

The following steps are continued from previous section.

  • Right click on solution and go to Add || New Item (Fig 03)

  • Select "LINQ to SQL Classes" from the templates, provide the DataContext name and hit "Add". It is always recommended to provide a database name (unless you are working with multiple databases). The following is the screenshot (Fig 04):

  • If not already open, open "Server Explorer" (go to View || Server Explorer) and connect to your database. Make sure that you have both tables (along with their relationship) as mentioned in the previous section. The following gives you a better idea (Fig 05):

  • Drag and drop "dept" and "emp" from "Server Explorer" on to the designer (Fig 06).

  • Make sure "Web.Config" is modified with the connection string (should be automatic).

Creating a simple LINQ to SQL application: fetching information onto a web page

The following steps are continued from the previous section

  • Open "Default.aspx" on drag and drop a button and gridview controls. Modify the code to look like the following:


<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="SampleVB._Default" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:Button ID="btnSelectStar" runat="server" Text="Select *" />

<asp:GridView ID="GridView1" runat="server">

</asp:GridView>

</div>

</form>

</body>

</html>

  • Once you have modified the above source, open the code behind "Default.aspx.vb" and copy the following code:


Imports System.Data.Linq

Partial Public Class _Default

Inherits System.Web.UI.Page


Protected Sub btnSelectStar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSelectStar.Click

Dim db As New SampleDBDataContext

Me.GridView1.DataSource = db.emps

Me.GridView1.DataBind()

End Sub

End Class


  • Make sure "Web.Config" is modified with the connection string (should be automatic).

That's all. Once you press F5, you should see the following output (Fig 07):


Creating a simple LINQ to SQL application: updating information to the database

Let us start adding a new web page to the project.

  • Add a new web page (.aspx) to your project

  • Design your web page to look like the following (Fig 08):

  • Modify your code behind to look like the following:


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 SampleDBDataContext

Me.GridView1.DataSource = db.emps

Me.GridView1.DataBind()

End Sub


Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSearch.Click

Try

Dim db As New SampleDBDataContext

'getting an existing row

Dim objEmp As emp = db.emps.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

Dim db As New SampleDBDataContext

'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}

db.emps.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


Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnUpdate.Click

Try

Dim db As New SampleDBDataContext

'getting an existing row

Dim objEmp As emp = db.Emps.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


Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnDelete.Click

Try

Dim db As New SampleDBDataContext

'getting an exiting row

Dim objEmp As emp = db.emps.SingleOrDefault(Function(p) p.empno = Me.txtEmpno.Text)

If objEmp IsNot Nothing Then

'delete the row

db.emps.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

Now you can observe that the above code is bit different from my previous article.

How about dealing with transactions? Does "LINQ to SQL" support transactions? The next section gives you the answer.

Creating a simple LINQ to SQL application: handling transactions using LINQ

Now that you are familiar with fetching and updating database tables using LINQ (in previous sections), it is time to work with transactions.

"LINQ to SQL" has built-in support for transactions. If we use "LINQ to SQL Designer," we don't even have to worry about transactions. If multiple rows are modified (irrespective of any number of tables), "LINQ to SQL" automatically encloses them in a transaction.

Let us start with another web page. Follow the steps below:

  • Add a new web page (.aspx) to your project. Call it "TransactionSample.aspx."

  • Design your web page as shown below (Fig 10):

  • Make modifications to the source to make it look like the following:


<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="TransactionSample.aspx.vb" Inherits="SampleVB.TransactionSample" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Untitled Page</title>

<style type="text/css">

.style1

{

width: 100%;

}

</style>

</head>

<body>

<form id="form1" runat="server">

<div>

<table class="style1">

<tr>

<td valign="top">

<asp:Button ID="btnRefreshDept" runat="server" Text="Refresh Dept" />

<asp:GridView ID="gvDept" runat="server">

</asp:GridView>

</td>

<td valign="top">

<asp:Button ID="btnRefreshEmp" runat="server" Text="Refresh Emp" />

<asp:GridView ID="gvEmp" runat="server">

</asp:GridView>

</td>

</tr>

</table>

<asp:Button ID="btnAddDeptEmp" runat="server" Text="Do Transaction" /><br />

<asp:Label ID="lblMsg" runat="server" ForeColor="Maroon"></asp:Label>


</div>

</form>

</body>

</html>


  • Turn to the code behind the page (TransactionSample.aspx.vb) and modify the code to look like the following:


Imports System.Data.Linq

Partial Public Class TransactionSample

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 btnRefreshDept_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnRefreshDept.Click

Dim db As New SampleDBDataContext

Me.gvDept.DataSource = db.depts

Me.gvDept.DataBind()

End Sub


Protected Sub btnRefreshEmp_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnRefreshEmp.Click

Dim db As New SampleDBDataContext

Me.gvEmp.DataSource = db.emps

Me.gvEmp.DataBind()

End Sub


Protected Sub btnAddDeptEmp_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAddDeptEmp.Click

Try

Dim db As New SampleDBDataContext

Dim depts As Table(Of dept) = db.depts


'create new dept

Dim NewDept As New dept

NewDept.deptno = 50

NewDept.dname = "Legal"


'create new emp

Dim NewEmp1 As New emp

NewEmp1.empno = 2001

NewEmp1.ename = "aaa"

NewEmp1.sal = "2500"

NewEmp1.deptno = 50


'create another emp

Dim NewEmp2 As New emp

NewEmp2.empno = 2002

NewEmp2.ename = "bbb"

NewEmp2.sal = "5500"

NewEmp2.deptno = 50


'add employees to dept

NewDept.emps.Add(NewEmp1)

NewDept.emps.Add(NewEmp2)


'add to context

db.depts.InsertOnSubmit(NewDept)


'save the changes

db.SubmitChanges()



Me.lblMsg.Text = "Saved successfully"

Catch ex As Exception

Me.lblMsg.Text = ex.Message

End Try

End Sub

End Class


Once executed, the output should look as follows (Fig 11):


The next section gives you an understanding of the transactions.

Explanation of handling transactions in LINQ to SQL

The "LINQ to SQL" framework automatically encloses the modifications into a transaction, if it is trying to handle more than one row at a time (say, submitting more rows to save to a database).

Let us try to understand each line from the previous section.


Dim db As New SampleDBDataContext

Dim depts As Table(Of dept) = db.depts


The above creates an instance to the database context. Through the context object, we interact with the database. In other words, it is the main interface. As "Department" is the parent table, I created a reference to the collection of "dept" models. This can be used to add "dept" objects directly to it. We can also do the same using "db.depts" directly.


Dim NewDept As New dept

NewDept.deptno = 50

NewDept.dname = "Legal"


Adding a new department involves creating a new "dept" object. The above does the same. It instantiates a "dept" object and provides the values for the properties.


'create new emp

Dim NewEmp1 As New emp

NewEmp1.empno = 2001

NewEmp1.ename = "aaa"

NewEmp1.sal = "2500"

NewEmp1.deptno = 50


'create another emp

Dim NewEmp2 As New emp

NewEmp2.empno = 2002

NewEmp2.ename = "bbb"

NewEmp2.sal = "5500"

NewEmp2.deptno = 50


Once the "Dept" object is ready, we need to add a few employees (say "emp" objects) to the newly created "dept" object. The above creates two new "emp" objects and provides the values for their properties.


NewDept.emps.Add(NewEmp1)

NewDept.emps.Add(NewEmp2)


As the two employees are related to the same department, we need to add those to the sub-collection of "Dept" object (which is nothing but the "Emps" collection). The above does the same.


db.depts.InsertOnSubmit(NewDept)

db.SubmitChanges()


The first line in the above sample adds the entire dept structure (along with employees) to the "depts" collection of the database context. Finally, we save it using the second line.

The "db.SubmitChanges()" opens a transaction. The transaction is implicitly handled as part of the "SubmitChanges" method.

Make sure that if the "SubmitChanges" method needs to work with the explicit transaction (say distributed), we can execute the statement in a separate "TransactionScope" enclosure as follows:


Using ts As New System.Transactions.TransactionScope

.

.

db.SubmitChanges()

.

.

End Using


I hope you enjoyed the article. Any suggestions, bugs, errors, enhancements, etc. are highly appreciated at http://jagchat.spaces.live.com

blog comments powered by Disqus
.NET ARTICLES

- .Net 4.5 Brings Changes
- Understanding Events in VB.NET
- Objects, Properties, Events and Methods in V...
- Install Visual Web Developer Express 2010
- Microsoft Gadgeteer an Open Source Alternati...
- Best DotNetNuke Modules
- Facebook Image Viewer in Visual Basic
- Murach`s ADO.NET 4 Database Programming with...
- 5 Must Have Visual Studio 2010 Extensions
- Dynamic Web Applications with ASP.NET Mono u...
- PDFSharp: HTML to PDF in ASP.NET 3.5 using V...
- Using the PDFSharp Library in ASP.NET 3.5 wi...
- Sending Email in ASP.NET 3.5 using VB.NET wi...
- ASP.NET 3.5 Role Based Security and User Aut...
- Creating ASP.NET Login Web Pages and Basic C...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 5 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials