Amiga500
Amiga500

Reputation: 6131

Delete records based on array list - LINQ

I have struggled a lot untill I reached this step. Basically, finally after certain criteria, I have an array with the ID's that I should remove from the DB.

This is the code that I have:

var ListOfIdThatNeedToBeRemoved = {id's};

I also have a table persons, that has PersonID. The persons I wish to delete is contained in ListOfIdThatNeedToBeRemoved variable.

I also have:

dbContext.tbl_persons

Any insight is appreciated :)

Upvotes: 0

Views: 455

Answers (2)

Tyler Jennings
Tyler Jennings

Reputation: 8911

I think you should be able to do something similar to:

using(dbContext context = new dbContext())
{
   foreach(var ID in ListOfIdThatNeedToBeRemoved)
   {
      context.tbl_persons.RemoveRange(context.tbl_persons.Where(x => x.id == ID));
   }
   context.SaveChanges();
}

Upvotes: 1

Robert McKee
Robert McKee

Reputation: 21487

using(dbContext context = new dbContext())
{
    context.tbl_persons.RemoveRange(context.tbl_persons.Where(x => ListOfIdThatNeedToBeRemoved.Contains(x.id)));
    context.SaveChanges();  
}

Upvotes: 2

Related Questions