views:

34

answers:

1

Given a set of entity ids, how can you efficiently delete the entities to which to ids represent, without first selecting the entity?

Here is some code, I am using now, but EF profiler is complaining at me for running N+1 queries:

    var ids = GetSelectedIds();

    foreach (var id in ids)
        db.Workshops.DeleteObject(db.Workshops.Single(x => x.Id == id));

    db.SaveChanges();
    BindWorkshops();
A: 

This helped EF profiler to stop complaining about N+1, but is there a better way?

var ids = GetSelectedIds();

foreach (var id in ids)
{
    var ws = new Workshop { Id = id };
    db.Workshops.Attach(ws);
    db.Workshops.DeleteObject(ws);
}

db.SaveChanges();
BindWorkshops();
Ronnie Overby
That's the most efficient way without dropping down to native SQL.
Craig Stuntz