EF 4 CTP 5:尝试删除实体时遇到问题

发布于 2024-10-19 14:22:58 字数 1608 浏览 0 评论 0原文

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

每个 Recipe 都包含一个 ICollection 类别,这些类别以多种方式链接 RecipesCategories 表。一对多关系。 RecipeCategory 包含相应的两个外键。

我的控制器和存储库逻辑的简化版本如下所示(为了简单起见,我已注释掉所有授权检查、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 替换为 ICollection。不小心,ReSharper 重构了 virtual 关键字。

但是,问题仍然存在 - 我无法从 Recipe 实体中删除 Category。以下代码不会将类别的删除持久保存到数据库中:

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

    _context.SaveChanges();
}

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

我做错了什么?

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

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

Every Recipe contains an ICollection<RecipeCategory> of categories that link the Recipes and the Categories table 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 have commented out all checks for authorization, null objects etc. for simplicity):

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

    return View("Deleted");
}

The repository's Remove method does nothing but the following:

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

Howevery, the code above does not work since I receive a System.InvalidOperationException every time I run it: Adding a relationship with an entity which is in the Deleted state is not allowed.

What does the error message stand for and how can I solve the problem? The only thing I try to achieve is deleting an entity.


@Ladislav: I have replaced ICollection<RecipeCategory> by ICollection<Category>. Accidentially, ReSharper refactored away the virtual keyword.

However, the problem remains — I cannot delete a Category from a Recipe entity. The following code does not persist the deletion of the categories to the database:

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

    _context.SaveChanges();
}

I have debugged the code and can confirm that the collections are modified correctly — that is, they contain no elements after the loop (I have also used the Clear() method). After calling SaveChanges(), they are populated again.

What am I doing wrong?

(Maybe it is important: I am using the Singleton pattern to only have one instance of the context.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

铃予 2024-10-26 14:22:58

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

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

I was able to solve the problem the 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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文