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

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

问题描述

我使用实体框架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);
        }

相反,我收到错误:


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

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天全站免登陆