You are on page 1of 10

Using LINQ to SQL to Add/Delete from

SQL Database in C#
Category: ASP.NET

Edited by: Charles Norona, cnorona1@fau.edu

Original article located at: http://www.programminghelp.com/web-development/asp-


net/using-linq-to-sql-to-add-delete-from-sql-database-in-c/

LINQ to SQL in ASP.NET 3.5

Introduction

In this article, we will be looking at one flavor of Microsoft's new introduction to the
.NET Framework, LINQ to SQL. LINQ (Language-Integrated Query) comes in a variety
of forms, including LINQ to XML and LINQ to Objects. In this article, we will be
looking at LINQ to SQL in Visual Studio.NET 2008. If you do not have 2008, you can
download the LINQ Preview for VS.NET 2005 direct from Microsoft.

In this article, we will create a LINQ to SQL Class to represent our SQL database, and
will be dealing with LINQ statements instead of working directly with SQL.

What we will learn in this article:

• How to connect to and retrieve data from a SQL database using LINQ;
• How to delete data from a SQL database using LINQ;
• How to add data to a SQL database using LINQ.

Please Note:
LINQ is integrated into ASP.NET 3.5 and does not require any additional downloads.
If you are using ASP.NET 2.0, certain extra steps may need to be taken that are not
covered in this article.

© ProgrammingHelp : Web Development and Programming Help Tutorials for Web


Developers
Getting Started
Before we begin coding, we will need to start a new project and create our database.
Open Visual Studio, and then goto File > New Website. Then choose your location and
give the website a name - LINQtoSQL will do.
When you click Ok, Visual Studio will create the necessary files and we will eventually
be provided with our ASPX page. To the right, we have our Solution Explorer. Right-
click the App_Data folder and choose Add New Item, then choose SQL Server Database.
Give it a name.

Next, open up the Server Explorer on the left (or View > Server Explorer), and right-click
the Tables folder on the database we just added, then click Add New Table.

© ProgrammingHelp : Web Development and Programming Help Tutorials for Web


Developers
We will then be provided with the table designer. Let's add three columns: id, name, city.
We will set the data types as int, varchar(50), varchar(50) respectively. We will also
make id the Primary Key and set its Identity Specification to Yes in the Column
Properties at the bottom. This will make the id column the unique identifier for each
record, which makes it easier for us to let .NET do all the work for us.
Now we can save the table, name it tblPeople, and then close it, which will bring us back
to our ASPX page.

Now we have our database ready, we will add some sample data. Right-click the table in
the Server Explorer and choose Show Table Data. Now let's add some sample data -
notice we don't need to complete the id column as it is auto-generated:

Now we have our database set up, we can build our LINQ to SQL Class. Right-click on
your project in Solution Explorer, and choose Add New Item. Then from the list, choose
LINQ to SQL Classes. Give it a name if you want, and when you click Ok it may ask you
if you want to place in the App_Code folder. If so, choose Yes.

© ProgrammingHelp : Web Development and Programming Help Tutorials for Web


Developers
We should then be provided with the Object Relational Designer:

This is where LINQ creates its class based on our input. We can add our database tables
and stored procedures to this designer and modify the relationships between the data, and
then Visual Studio will create the class or classes based upon the layout.
For this example, we only have one table to work with, so the design is going to be very
simple. From Server Explorer, drag the table onto the main area of the designer. Our table
should be graphically represented like so:

© ProgrammingHelp : Web Development and Programming Help Tutorials for Web


Developers
Now we can save the changes we made and close the designer.
Let's now drag a LinqDataSource control onto the ASPX page, and we can use the Smart
Tag in design view to configure the data source. We want to use the
DataClassesDataContext we just created:

© ProgrammingHelp : Web Development and Programming Help Tutorials for Web


Developers
When we are done with the LinqDataSource Wizard, we should be presented with a new
Smart Tag. Check Enable Delete and Enable Insert:

Now we have created our LINQ to SQL Class and linked it to our LinqDataSource, and
enabled Deletions and Inserts. Notice that we only need to specify what we want, and
Visual Studio will do the hard work for us, behind the scenes.

© ProgrammingHelp : Web Development and Programming Help Tutorials for Web


Developers
Next up, let's create a means for us to add new records to the database. We'll modify the
ASPX page to include two textboxes and a submit button (remember, we don't need to
input the id field, as it's auto-generated):

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


Name: <asp:TextBox ID="txtName" runat="server" /><br />
City: <asp:TextBox ID="txtCity" runat="server" /><br />
<asp:Button ID="butAdd" runat="server" Text="Add" />
<br />
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="DataClassesDataContext" EnableDelete="True"
EnableInsert="True" TableName="tblPeoples">
</asp:LinqDataSource>
</form>

We can use a DataGrid to display the records from the database. We can either drag one
on from the toolbox and use the Smart Tag to assign the datasource, or simply type it in
ourselves:

<asp:DataGrid
ID="DataGrid1" runat="server" DataSourceID="LinqDataSource1"
Width="334px">
</asp:DataGrid>

Now if we right-click our Default.aspx in the Solution Explorer and choose View in
Browser, we will be presented with an input form and a neat table displaying the data
from the database. This is similar to using the SqlDataSource and DataGrid or GridView
controls, but LINQ has so much more to offer and makes it a lot easier for us to
communicate with and manipulate data, as we will see in the rest of this article.

At present, the web application is just displaying data - no real functionality. Let us now
add the functionality to add new records to the database.

© ProgrammingHelp : Web Development and Programming Help Tutorials for Web


Developers
Go into the design view of the ASPX page and double-click on the button to create the
event handler for the click event. We will use LINQ to add the contents of the textboxes
into the SQL database. We use the connection string that was added to our Web.config
when we created the LinqDataSource, and we use the LINQ to SQL Class to reference
our database. The class can be seen as a representation of our database, which we can
make changes to without making changes to the original database. This allows us to make
multiple changes without making multiple calls to the database. We can then commit
changes back to the database with the SubmitChanges() method, which is a member of
the DataContext class.

protected void butAdd_Click(object sender, EventArgs e)


{
string connectionString =
ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ToString
();
DataClassesDataContext dataContext = new
DataClassesDataContext(connectionString);

tblPeople tblP = new tblPeople();


tblP.name = txtName.Text;
tblP.city = txtCity.Text;
dataContext.tblPeoples.InsertOnSubmit(tblP);
dataContext.SubmitChanges();
DataGrid1.DataBind();
}
Note: If you forget the name of the context class you are using, it can be found in the
class view. Also, make sure that your connection string name matches the one found in
your web.config file or else you code will encounter an exception.

Note that our database isn't modified until the SubmitChanges() method is called. This
means we can make multiple changes without even making a call to the database, which
reduces server load and processing time.
In our last line, we call the DataGrid to bind the data source again, so that we can see the
newest data.

We can now move onto deletions. We want to add the ability to delete any record in the
database. We will do this by populating a DropDownList with the names in the database,
and then use a delete button to delete the selected record. We can use the same
DataSource for the DropDown, so the code would look something like this:

<asp:DropDownList
ID="DropDownList1" runat="server" AutoPostBack="True"
DataSourceID="LinqDataSource1" DataTextField="name"
DataValueField="id">
</asp:DropDownList>
<br />

© ProgrammingHelp : Web Development and Programming Help Tutorials for Web


Developers
<asp:Button ID="butDelete" runat="server" Text="Delete" onclick="butDelete_Click" />

In a similar way to how we coded the addition of new records, we add code to the delete
button. Double click the delete button in design view and then add the following code.

protected void butDelete_Click(object sender, EventArgs e)


{
DataClassesDataContext db = new DataClassesDataContext();
var selectedID = Convert.ToInt16(DropDownList1.SelectedValue);
tblPeople toDelete = db.tblPeoples.Single(p => p.id == selectedID);
db.tblPeoples.DeleteOnSubmit( toDelete );
db.SubmitChanges();

DropDownList1.DataBind();
}

Again, we are using LINQ to interact with and modify the class representing our database
then we submit changes back to the database. Notice that we also bind our DropDown
again, when we're done, to update the datasource. We also need to bind the GridView
here, and also bind the DropDown on the butAdd handler to make sure our datasources
are always up to date.
So our code-behind will look like this:

using System;
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 _Default : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{

protected void butAdd_Click(object sender, EventArgs e)


{
string connectionString =
ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].T

© ProgrammingHelp : Web Development and Programming Help Tutorials for Web


Developers
oString();
DataClassesDataContext dataContext = new
DataClassesDataContext(connectionString);

tblPeople tblP = new tblPeople();


tblP.name = txtName.Text;
tblP.city = txtCity.Text;
dataContext.tblPeoples.InsertOnSubmit(tblP);
dataContext.SubmitChanges();

DataGrid1.DataBind();
DropDownList1.DataBind();
}

protected void butDelete_Click(object sender, EventArgs e)


{
DataClassesDataContext db = new DataClassesDataContext();
var selectedID = Convert.ToInt16(DropDownList1.SelectedValue);
tblPeople toDelete = db.tblPeoples.Single(p => p.id == selectedID);
db.tblPeoples.DeleteOnSubmit( toDelete );
db.SubmitChanges();

DropDownList1.DataBind();
DataGrid1.DataBind();
}
}

And now we can run our web application and be able to view, add and delete records
from the SQL database without writing any SQL statements.

What we have Learned

We have learned that we can easily use LINQ to interact with a SQL database, making it
easy for us to add new records to the database as well as deleting records from it.

© ProgrammingHelp : Web Development and Programming Help Tutorials for Web


Developers