开发者

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?


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.


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.


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();


How about something like,

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

context.saveChanges();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜