In this article I will explain with an example, how to delete multiple records 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 records to be deleted.
Button – For deleting multiple records.
The Button has been assigned with an OnClick event handler.
<form id="form1" runat="server">
<asp:TextBox ID="txtId" runat="server"></asp:TextBox>
<asp:Button runat="server" Text="Delete" OnClick="OnDelete" />
</form>
Deleting multiple records from Database using Entity Framework
The following event handler is executed when the Delete Button is clicked.
Inside the event handler, CustomerIds to be deleted are fetched from the TextBox and converts them into an Integer Array.
Then based on the Array, Customers are referenced and passed to the
RemoveRange method of
Entity Framework and the
SaveChanges method of
Entity Framework is called which updates the changes to the database.
Finally, success message is displayed in
JavaScript Alert Message Box using
RegisterStartupScript method.
C#
protected void OnDelete(object sender, EventArgs e)
{
using (AjaxSamplesEntities entities = new AjaxSamplesEntities())
{
int rowsAffected = 0;
int[]customerIds = Array.ConvertAll(txtId.Text.Split(','), Int32.Parse);
// Referencing Customers.
List<Customer> deletedCustomers = entities.Customers.Where(customer => customerIds.Contains(customer.CustomerId)).ToList();
if (deletedCustomers != null)
{
// Deleting Customers.
rowsAffected = entities.Customers.RemoveRange(deletedCustomers).Count();
entities.SaveChanges();
}
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Customers Table has been truncated.');", true);
}
txtId.Text = string.Empty;
}
VB.Net
Protected Sub OnDelete(sender As Object, e As EventArgs)
Using entities As AjaxSamplesEntities = New AjaxSamplesEntities()
Dim rowsAffected As Integer = 0
Dim customerIds As Integer() = Array.ConvertAll(txtId.Text.Split(","c), Function(s) Int32.Parse(s))
' Referencing Customers.
Dim deletedCustomers As List(Of Customer) = entities.Customers.Where(Function(customer)customerIds.Contains(customer.CustomerId)).ToList()
If deletedCustomers IsNot Nothing Then
' Deleting Customers.
rowsAffected = entities.Customers.RemoveRange(deletedCustomers).Count()
entities.SaveChanges()
End If
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Customers Table has been truncated.');", True)
End Using
txtId.Text = String.Empty
End Sub
Screenshot
Records After Deleting
Downloads