Reputation: 124
So I'm in trouble with this error:
An unhandled exception of type 'System.Data.Entity.ModelConfiguration.ModelValidationException' occurred in EntityFramework.dll.
Here is the code:
public ActionResult SaveItems(string[] fooItems, int category_id)
{
foreach (item item in DB.items)
{
if (item.category_id == category_id)
{
if(item != null)
DB.items.Remove(item);
DB.SaveChanges();
}
}
}
I'm trying to remove an item from the database, and save changes after that, when I get this error.
Any help is appreciated.
Thanks!
Upvotes: 1
Views: 1754
Reputation: 6844
You've got a couple issues:
I would use the following:
public ActionResult SaveItems(string[] fooItems, int category_id)
{
var itemsToRemove = DB.items.Where(e => e.category_id == category_id)
.ToList();
foreach (var item in itemsToRemove)
{
DB.items.Remove(item);
}
DB.SaveChanges();
}
Upvotes: 0
Reputation: 9155
As someone correctly mentioned in the comments, you cannot make changes to the underlying list while using a foreach loop. Change your action method to this:
public ActionResult SaveItems(string[] fooItems, int category_id)
{
var itemsToRemove = DB.items.Where(i => i.category_id == category_id).ToList();
DB.items.RemoveRange(itemsToRemove);
DB.SaveChanges();
}
Upvotes: 3