Delete multiple records using Entity Framework in ASP.Net using C# and VB.Net

Destinykid
 
on Feb 19, 2021 10:59 AM
Sample_296624.zip
807 Views

Greetings sir, I trust you are doing well. Please, my question goes like this 

Assuming I have a Table with ColName as one of the Columns and I have 10 records and 8 out of the 10 records contains Destiny under colName... This means that Destiny occurred 8 times...in 10 records/rows 

 

How do I run a query to delete all the rows with Destiny under ColName

I have tried select(e=>e.colName == "Destiny")

But nothing I have tried worked please help me thanks sir

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Feb 20, 2021 01:54 AM
on Feb 20, 2021 01:55 AM

Hi Destinykid,

Use Contains function.

Check this example. Now please take its reference and correct your code.

HTML

<asp:TextBox runat="server" ID="txtName" />
<asp:Button ID="btnDelete" Text="Delete" runat="server" OnClick="OnDelete" />
<asp:GridView runat="server" ID="gvCustomers"></asp:GridView>

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        CustomerEntities entity = new CustomerEntities();
        gvCustomers.DataSource = entity.Customers.ToList();
        gvCustomers.DataBind();
    }
}

protected void OnDelete(object sender, EventArgs e)
{
    CustomerEntities entity = new CustomerEntities();
    List<Customer> customers = entity.Customers.Where(c => c.Name.Contains(txtName.Text.Trim())).ToList();
    entity.Customers.RemoveRange(customers);
    entity.SaveChanges();
    gvCustomers.DataSource = entity.Customers.ToList();
    gvCustomers.DataBind();
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim entity As CustomerEntities = New CustomerEntities()
        gvCustomers.DataSource = entity.Customers.ToList()
        gvCustomers.DataBind()
    End If
End Sub

Protected Sub OnDelete(ByVal sender As Object, ByVal e As EventArgs)
    Dim entity As CustomerEntities = New CustomerEntities()
    Dim customers As List(Of Customer) = entity.Customers.Where(Function(c) c.Name.Contains(txtName.Text.Trim())).ToList()
    entity.Customers.RemoveRange(customers)
    entity.SaveChanges()
    gvCustomers.DataSource = entity.Customers.ToList()
    gvCustomers.DataBind()
End Sub