Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete multiple Items from a List of Id's using Entity Framework

I need to delete multiple Ids from a List of Ids.

public IHttpActionResult Delete(List<string> IDs)
{
    DealBazarEntities.Restaurants.RemoveRange(IDs);
    DealBazarEntities.SaveChanges();
}

But RemoveRange does not allow multiple ids , it expect only List<entities>.

Yes, I know that , if I send list of entities to server instead of sending List of ids , Then I can easily accomplish this. But I don't like that.

Again, I don't want to use foreach loop to loop through every Ids.

like image 605
Bimal Das Avatar asked Feb 14 '16 07:02

Bimal Das


People also ask

How do I delete a list in Entity Framework?

Delete a Record In Connected Scenario, you can use the Remove or RemoveRange method to mark the record as Deleted . In Disconnected Scenario, you can attach it to the context and set its state as Deleted . Calling SaveChanges will send the delete query to the database.

How delete multiple records from database in MVC?

Choose your data connection then select your database then click Next then select Tables then enter the Model namespace then click Finish. Add a Controller or use the default Home controller. I used the default Home controller. Add a new action into your controller to delete rows.

How do I use RemoveRange in Entity Framework?

RemoveRange() method attaches a collection of entities with Deleted state, which in turn will execute the DELETE command for all entities on SaveChanges() . Adding or removing entities using the AddRange and RemoveRange methods improves the performance.

How do I delete all records from a table in Entity Framework?

The Other quickest simple option to delete all the rows in a table in entity framework is to use the TRUNCATE table query and execute it with the ExecuteSqlCommand as shown below. dbContext. Database. ExecuteSqlCommand("TRUNCATE TABLE Customer");


1 Answers

According to the answer of Stephen Muecke's answer given into comment section in the question , the solution is :

DealBazarEntities.Restaurants.RemoveRange
(DealBazarEntities.Restaurants.Where(r => IDs.Contains(r.ID)));
like image 195
Bimal Das Avatar answered Oct 06 '22 17:10

Bimal Das