NoName
NoName

Reputation: 124

System.Data.DataException error occurred in EntityFramework.dll in asp mvc

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!

Upvotes: 1

Views: 1754

Answers (2)

Vlad274
Vlad274

Reputation: 6844

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

Upvotes: 0

ataravati
ataravati

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

Related Questions