entity-framework - EF 4 CTP 5 : Trouble trying to remove an entity

标签 entity-framework code-first entity-framework-ctp5 ef-code-first

我创建了一个名为 Recipe 的模型 POCO 类;一个对应的 RecipeRepository持久化这些对象。我在现有数据库上使用 Code First。

Recipe包含 ICollection<RecipeCategory>链接 Recipes 的类别和 Categories表中的多对多关系。 RecipeCategory包含对应的两个外键。

我的 Controller 和存储库逻辑的简化版本如下所示(为简单起见,我已注释掉所有授权检查、null 对象等):

public ActionResult Delete(int id)
{
    _recipeRepository.Remove(id);

    return View("Deleted");
}

存储库的 Remove方法只执行以下操作:
public void Remove(int id)
{
    Recipe recipe = _context.Recipes.Find(id);
    _context.Recipes.Remove(recipe);
    _context.SaveChanges();
}

然而,上面的代码不起作用,因为我收到了 System.InvalidOperationException每次运行时:不允许添加与处于已删除状态的实体的关系。

错误消息代表什么,我该如何解决问题?我试图实现的唯一目标是删除一个实体。

@Ladislav:我已经更换了 ICollection<RecipeCategory>来自 ICollection<Category> .意外地,ReSharper 重构了 virtual关键词。

但是,问题仍然存在——我无法删除 Category来自 Recipe实体。以下代码不会将类别的删除持久化到数据库:
private void RemoveAllCategoriesAssignedToRecipe()
{
    foreach (Category category in _recipe.Categories.ToArray())
    {
        _recipe.Categories.Remove(category);
        category.Recipes.Remove(_recipe);
    }

    _context.SaveChanges();
}

我已经调试了代码并且可以确认集合被正确修改——也就是说,它们在循环之后不包含任何元素(我也使用了 Clear() 方法)。调用后SaveChanges() ,它们再次被填充。

我究竟做错了什么?

(也许这很重要:我使用单例模式来只有一个上下文实例。)

最佳答案

我能够通过以下方式解决问题:

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

关于entity-framework - EF 4 CTP 5 : Trouble trying to remove an entity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5134659/

相关文章:

c# - Entity Framework 代码优先 : How can I create a One-to-Many AND a One-to-One relationship between two tables?

entity-framework - Entity Framework TPH 继承错误 :

asp.net-mvc - 在这种模式中,业务逻辑应该在哪里?

entity-framework - 我看不到带有 POCO 类的 DbContext 中的存储过程

image - 使用 ASP.NET MVC 3 和 Entity Framework 4.1 Code First 在 SQL CE 4.0 中存储图像时出错

entity-framework-4.1 - EF Code First 抽象关系?

entity-framework - 如何使用EF4 Code First在同一张表中进行多对多

c# - EntityFramework 迁移未从列中删除 'IsRequired'

c# - Entity Framework 数据库提供程序兼容性错误

c# - 使用 Entity Framework 仅更新数据库中的某些列