code first - EF 4 CTP 5: Trouble trying to remove an entity -
i have created model poco class called recipe
; corresponding reciperepository
persists these objects. using code first on top of existing database.
every recipe
contains icollection<recipecategory>
of categories link recipes
, categories
table in many-to-many relationship. recipecategory
contains corresponding 2 foreign keys.
a simplified version of controller , repository logic looks (i have commented out checks authorization, null
objects etc. simplicity):
public actionresult delete(int id) { _reciperepository.remove(id); return view("deleted"); }
the repository's remove
method nothing following:
public void remove(int id) { recipe recipe = _context.recipes.find(id); _context.recipes.remove(recipe); _context.savechanges(); }
howevery, code above not work since receive system.invalidoperationexception
every time run it: adding relationship entity in deleted state not allowed.
what error message stand , how can solve problem? thing try achieve deleting entity.
@ladislav: have replaced icollection<recipecategory>
icollection<category>
. accidentially, resharper refactored away virtual
keyword.
however, problem remains — cannot delete category
recipe
entity. following code not persist deletion of categories database:
private void removeallcategoriesassignedtorecipe() { foreach (category category in _recipe.categories.toarray()) { _recipe.categories.remove(category); category.recipes.remove(_recipe); } _context.savechanges(); }
i have debugged code , can confirm collections modified correctly — is, contain no elements after loop (i have used clear()
method). after calling savechanges()
, populated again.
what doing wrong?
(maybe important: using singleton pattern have 1 instance of context.)
i able solve problem following way:
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(); }
Comments
Post a Comment