c# - EF 4.1 : Removing child object from collection does not delete it - why?

标签 c# .net entity-framework poco entity-framework-4.1

我有一些错误: EF 4: Removing child object from collection does not delete it - why?

当我从父项中删除一个子项时,当我调用 SaveChanges() 时该子项被删除,它会给出以下错误消息:

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

但是对于 DbContext 和 EF 4.1,“context.DeleteObject(recipe)”不存在。

有什么建议吗?

[编辑]

    public void UpdateWithAttributes(Model model, IEnumerable<Entity> entities)
    {
        var modelOriginal = this.unitOfWork.Model.GetById(model.IModel);

        this.unitOfWork.Context.Entry(modelOriginal).CurrentValues.SetValues(model);
        UpdateEntityAttributeAssociations(modelOriginal, entities);

        this.unitOfWork.Commit();
    }

    public void UpdateEntityAttributeAssociations(Model model, IEnumerable<Entity> current)
    {
        unitOfWork.Context.Entry(model).Collection(m => m.Entities).Load();
ICollection<Entity> original = model.Entities; // perhaps .ToList() necessary

        // delete
        if (original != null)
        {
            List<Entity> toDelete = GetToDelete(original, current);

            foreach (Entity originalEntityToDelete in toDelete)
            {
                unitOfWork.Context.Entity.Remove(originalEntityToDelete);
            }
        }

        // add, update
        if (current != null)
        {
            foreach (Entity currentEntity in current)
            {
                // No need to set the UpdatedWhen. The trigger on the table will handle that.
                if (original.Where(originalEntity => originalEntity.IEntity == currentEntity.IEntity).FirstOrDefault() == null)
                {
                    model.Entities.Add(currentEntity);
                }
            }
        }
    }

最佳答案

你必须调用:

context.Recipes.Remove(recipe);

在哪里RecipesDbSet<Recipe> .

关于c# - EF 4.1 : Removing child object from collection does not delete it - why?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6125871/

相关文章:

c# - 需要帮助理解 _set_security_error_handler()

c# - 从 asp.net 中的表单插入到表中

c# - 从另一个线程调用 Windows 窗体 (.Net)

c# - 检测 web.config 已更改

c# - "StyleCop "SA1300 未在 GlobalSuppressions.cs 类中抑制

c# - 我在 ToolStripSeparator c# 中看不到 RenderMode-property

c# - WCF 服务的 VS2003 Web 引用有额外的 "IdSpecified"参数

entity-framework - 包括不使用连接实体

visual-studio-2010 - 使用 Entity Framework ,允许空属性不在模型中更新

c# - Entity Framework 如何从 Datacontext 中分离所有特定类型的对象?