1

So I'm in trouble with this error:

An unhandled exception of type 'System.Data.Entity.ModelConfiguration.ModelValidationException' occurred in EntityFramework.dll.

enter image description here

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!

1
  • 2
    you can't mess with the underlying list while using a foreach as the yield will get thrown off Commented Nov 6, 2015 at 18:57

2 Answers 2

3

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();
}
Sign up to request clarification or add additional context in comments.

Comments

0

You've got a couple issues:

  1. You're modifying a list from within the foreach (as noted by Alex Krupka in a comment)
  2. You're calling SaveChanges after every removal
  3. This code loads each item one at a time, resulting in a lot of unnecessary calls to the DB
  4. You're removing items from a method called "SaveItems"

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.