EF 4:从集合中删除子对象不会删除它 - 为什么? [英] EF 4: Removing child object from collection does not delete it - why?

查看:30
本文介绍了EF 4:从集合中删除子对象不会删除它 - 为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Entity Framework 4 并且我有父子关系与级联删除"集.所以我希望当我从父级中删除一个孩子时,当我调用 SaveChanges() 时,这个孩子会被删除.

I use Entity Framework 4 and I have parent - child relation with "Cascade Delete" set. So i would expect when i remove a child from the parent that the child is deleted when i call SaveChanges().

        cuRepository.Attach(_controlUnit);
        foreach (var recipe in recipes) {
            _controlUnit.Recipes.Remove(recipe);
            //repository.DeleteObject(recipe);
        }

相反,我收到一个错误:

Instead i get an error:

发生System.InvalidOperationException Message=操作失败:无法更改关系,因为以下一项或多项外键属性不可为空.当对某项进行更改时关系,相关的外键属性设置为空值.如果外键不支持空值,新的关系必须定义,必须为外键属性分配另一个非空值,否则必须删除不相关的对象.

System.InvalidOperationException occurred Message=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.

当我明确删除孩子时(见注释行),一切都很好.我错过了什么?

When I explicitly delete the children (see commented line), all is fine. What am I missing?

推荐答案

您没有使用 remove 语句删除对象.相反,您正在尝试更改记录并使其成为孤立记录(通过将外键设置为 null).数据库对该列有一个非空约束并阻止您这样做.

You aren't deleting the object with the remove statement. Instead you are attempting to alter a record and make it an orphan (by setting the foreign key to null). The database has a non-null constraint on that column and prevents you from doing so.

这篇关于EF 4:从集合中删除子对象不会删除它 - 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆