EF 4 CTP 5: Problem Trying to Delete an Object

I created a model of a POCO class called Recipe ; the corresponding RecipeRepository object stores these objects. I am using Code First on top of an existing database.

Each Recipe contains an ICollection<RecipeCategory> categories that link the Recipes table and Categories in a many-to-many relationship. RecipeCategory contains the corresponding two foreign keys.

A simplified version of my controller and repository logic looks like this (I just commented out all the checks for authorization, null objects, etc.):

 public ActionResult Delete(int id) { _recipeRepository.Remove(id); return View("Deleted"); } 

The Remove repository method does nothing but the following:

 public void Remove(int id) { Recipe recipe = _context.Recipes.Find(id); _context.Recipes.Remove(recipe); _context.SaveChanges(); } 

In any case, the code above does not work, since I get a System.InvalidOperationException every time I run it: adding a relationship with an entity in the "Deleted" state is not allowed.

What does the error message mean and how can I solve the problem? The only thing I'm trying to achieve is to delete an object.


@Ladislav: I replaced ICollection<RecipeCategory> with ICollection<Category> . Incidentally, ReSharper reorganized the virtual .

However, the problem remains - I cannot remove the Category from the Recipe object. The following code does not save the removal of categories in the database:

 private void RemoveAllCategoriesAssignedToRecipe() { foreach (Category category in _recipe.Categories.ToArray()) { _recipe.Categories.Remove(category); category.Recipes.Remove(_recipe); } _context.SaveChanges(); } 

I debugged the code and can confirm that the collections were changed correctly, that is, they do not contain elements after the loop (I also used the Clear() method). After calling SaveChanges() they are filled again.

What am I doing wrong?

(Maybe this is important: I use the Singleton pattern to have only one instance of the context.)

+4
source share
1 answer

I managed to solve the problem as follows:

 private void RemoveAllCategoriesAssignedToRecipe() { foreach (Category category in _recipe.Categories.ToArray()) { Category categoryEntity = _categoryRepository.Retrieve(category.CategoryID); var recipesAssignedToCategory = categoryEntity.Recipes.ToArray(); categoryEntity.Recipes.Clear(); foreach (Recipe assignedRecipe in recipesAssignedToCategory) { if (assignedRecipe.RecipeID == _recipe.RecipeID) { continue; } categoryEntity.Recipes.Add(assignedRecipe); } _context.Entry(categoryEntity).State = EntityState.Modified; } _recipe.Categories.Clear(); _context.SaveChanges(); } 
0
source

Source: https://habr.com/ru/post/1341532/


All Articles