Reputation: 479
I am trying to delete multiple records using MVC. I have tried many ways. Like
_db.Categories.Where(p => p.CategoryID == catid)
.ToList().ForEach(p => _db.Categories.Remove(p));
_db.SaveChanges();
OR
foreach (Category item in _db.Categories.Where(x => x.CategoryID == catid))
_db.Categories.Remove(item);
_db.SaveChanges();
In both the cases only the last record has been deleted. I think the foreach
statement is not working.
I don't want to use for statement (like below) which is working well:
if (id != null)
{
for (int i = 0; i <= id.Length - 1; i++)
{
category = _db.Categories.Find(id[i]);
_db.Categories.Remove(category);
}
_db.SaveChanges();
}
Any suggestion will be thankfully accepted.
Partha
Upvotes: 2
Views: 632
Reputation: 11317
foreach statement is not working
It's working. But according to your where condition you will remove only one type of category
....Where(p => p.CategoryID == catid) // I assume that catid is a scalar value like integer
If id
is an array of Categories ids you want to remove, you can use Contains
:
foreach (Category item in _db.Categories.Where(x => id.Contains(x.CategoryID) ).ToList())
_db.Categories.Remove(item);
_db.SaveChanges();
Upvotes: 0
Reputation: 2502
A cleaner solution would be to remove a group of items using the RemoveRange() function. Simply select your items with linq from your DbSet, then call RemoveRange(yourItems). This way you only need to modify your dbset once, then save your context.
var itemsToRemove = _db.Categories.Where(p => p.CategoryID == catid);
_db.Categories.RemoveRange(itemsToRemove));
_db.SaveChanges();
Upvotes: 1