In this article I will explain with an example, how to delete from
Database using
Entity Framework in ASP.Net.
Database
I have made use of the following table Customers with the schema as follow.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Configuring and connecting Entity Framework to database
HTML Markup
The HTML Markup consists of following controls:
TextBox – For capturing CustomerId of the Customer record to be deleted.
Button – For deleting the record.
The Button has been assigned with an OnClick event handler.
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="width: 60px">Id<br />
<asp:TextBox ID="txtCustomerId" runat="server" Width="50px"></asp:TextBox>
</td>
<td style="width: 200px">
<br />
<asp:Button Text="Delete" runat="server" OnClick=" OnDelete" />
</td>
</tr>
</table>
Deleting records from Database using Entity Framework
The following event handler is executed when the Delete Button is clicked.
Inside the event handler, CustomerId is fetched from the TextBox.
The CustomerId value is used to reference the Customer record using
Entity Framework.
The fetched Customer object is passed to the
Remove method of
Entity Framework and the
SaveChanges method of
Entity Framework is called which updates the changes to the database.
Finally, based on whether record is deleted or not, an appropriate message is displayed in
JavaScript Alert Message Box using
RegisterStartupScript method.
C#
protected void OnDelete(object sender, EventArgs e)
{
int id = int.Parse(txtCustomerId.Text);
using (AjaxSamplesEntities entities = new AjaxSamplesEntities())
{
var deleteCustomer = (from customer in entities.Customers
where customer.CustomerId == id
select customer).FirstOrDefault();
if (deleteCustomer != null)
{
entities.Customers.Remove(deleteCustomer);
entities.SaveChanges();
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Customer record deleted.');", true);
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Customer not found.');", true);
}
}
}
VB.Net
Protected Sub OnDelete(sender As Object, e As EventArgs)
Dim id As Integer = Integer.Parse(txtCustomerId.Text)
Using entities As AjaxSamplesEntities = New AjaxSamplesEntities()
Dim deleteCustomer = (From customer In entities.Customers
Where customer.CustomerId = id
Select customer).FirstOrDefault()
If deleteCustomer IsNot Nothing Then
entities.Customers.Remove(deleteCustomer)
entities.SaveChanges()
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Customer record deleted.');", True)
Else
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Customer not found.');", True)
End If
End Using
End Sub
Screenshot
Downloads