我有一个 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
会更好。
查看更多详情:
关于c# - 代码首先拒绝级联删除实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30522170/