BrunoLM
BrunoLM

Reputation: 100331

How to delete elements by ID?

I have a list of ids

IEnumerable<long> ids

How can I delete from a table where the ID matches?

Upvotes: 2

Views: 287

Answers (4)

Bala R
Bala R

Reputation: 108957

How about something like,

context.Entities.Where(e => ids.Contains(e.id))
                .ToList()
                .ForEach(e => context.SampleEntities.DeleteObject(e) );

context.saveChanges();

Upvotes: 0

msarchet
msarchet

Reputation: 15242

Generically

var db = GetYourDBContext();
var ItemsToDelete = (from id in ids
                     from item in db.TableWithItems
                     where item.id == id
                     select item).ToList();

foreach (Item item in ItemsToDelete)
    db.DeleteObject(item);

db.SaveChanges();

Upvotes: 0

KeithS
KeithS

Reputation: 71573

The "standard" way according to the MSDN docs is to use those IDs to pull up each of the objects, then delete them with the DeleteObject command:

context.Where(x=>ids.Contains(x.Id)).ToList().ForEach(context.DeleteObject);

This will produce N+1 roundtrips to the DB. This is a common downside of ORMs; they're excellent at 99% of everyday use of SQL by an app (querying for results, creating/updating/deleting single objects) but are not really designed for these bulk operations.

You could also construct a query using ExecuteStoreCommand, where you "DELETE FROM table WHERE id IN @p1" and specify the list of IDs as a parameter.

Upvotes: 5

BrokenGlass
BrokenGlass

Reputation: 160902

Assuming you have Id as primary key in your entities and you have an entity called SampleEntity you could do something like this:

foreach(long id in ids)
{
  var sampleEntity = context.SampleEntities.SingleOrDefault( e => e.Id == id);
  if(sampleEntity!=null)
     context.SampleEntities.DeleteObject(sampleEntity);
}
context.SaveChanges();

EF does not support batch operation, so you will have to delete entities one by one, or alternatively do a direct store query (SQL) to make the deletion.

Upvotes: 0

Related Questions