gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:54:27 24 4
gpt4 key购买 nike

我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com