c# - 代码首先拒绝级联删除实体

标签 c# entity-framework ef-code-first

我有一个 Parent 实体,它与一个 Child 实体存在 0 对多的关系。当我删除父级时,我希望它自动级联删除所有附加的子级。尝试这样做会出现以下异常...

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.

我不明白关于设置空引用的消息。由于级联删除,子项将被删除,因此无需将任何子项设置为具有空引用。

我的两个简单实体定义为...

public class Parent
{
    [Key]
    public int Id { get; set; }
    public virtual ICollection<Child> Children { get; set; }
}

public class Child
{
    [Key]
    public int Id { get; set; }
    public int ParentId { get; set; }
    public virtual Parent Parent { get; set; }
}

用下面的映射...

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Child>()
        .HasRequired(x => x.Parent)
        .WithMany(x => x.Children)
        .HasForeignKey(x => x.ParentId)
        .WillCascadeOnDelete(true);
}

查看生成的数据库,确实将外键关系标记为级联删除。所以数据库模式看起来很好。抛出错误的实际代码...

Parent p = context.Parents.Find(id);
context.Entry<Parent>(p).State = System.Data.Entity.EntityState.Deleted;
context.SaveChanges();

有什么想法吗?

最佳答案

您的错误是由 Entity Framework 产生的,而不是由您的数据库产生的。

问题是您使用的是 context.Entry<Parent>(p).State = EntityState.Deleted而不是 context.Parents.Remove(p) .主要区别在于调用 Remove对于加载到上下文中的具有所需关系的任何子级,父级处理将实体状态设置为已删除。 State = EntityState.Deleted没有。

在您的情况下,您可能有一些相关的 Child加载到上下文中的实体和 EF 正在提示孤儿。如果您没有加载任何子项,DELETE 语句将发送到数据库,数据库将正常处理级联删除。

使用 DbSet.Remove会更好。

查看更多详情:

Delete parent with children in one to many relationship

关于c# - 代码首先拒绝级联删除实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30522170/

相关文章:

c# - 为什么 Enum.ToString 不能作为属性参数字符串类型的常量字符串接受?

c# - 上传到 Azure Blob 存储的 MP4 视频文件无法播放

c# - LINQ 的 WHERE 子句下的 IF ELSE 语句

c# - Entity Framework 和多线程的 NullReferenceException

mysql - 初始添加迁移认为数据库已经是最新的

c# - cssclass 不适用于复选框列表

c# - 具有值或 null 的 Entity Framework LINQ

c# - LINQ Order By Descending with Null Values on Bottom

entity-framework - Entity Framework 代码优先忽略连接字符串,而是使用 IIS

c# - Orderby Ascending on a list 错误asp.net