Delete multiple records using Entity Framework in ASP.Net

Last Reply 3 months ago By pandeyism

Posted 3 months ago

hello,

i have this link query

  var q = (from ue in db.UserExpertises
 where ue.UserName == Page.User.Identity.Name
 select ue);

it returns more than one value i want to loop each value and delete the records from databsae please advice

Posted 3 months ago

Hi nauna,

Refer below code.

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    TestEntities entities = new TestEntities();
    var result = (from cust in entities.CustomerTests
                    where cust.CustomerId >=2
                    select cust).ToList();
    foreach (var item in result)
    {
        entities.DeleteObject(item);
        entities.SaveChanges();
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim entities As TestEntities = New TestEntities()
    Dim result = (From cust In entities.CustomerTests Where cust.CustomerId >= 2 Select cust).ToList()
    For Each item In result
        entities.DeleteObject(item)
        entities.SaveChanges()
    Next
End Sub