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.
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.
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.
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.
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");
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With