gpt4 book ai didi

c# - EF 可以自动删除孤立的数据,其中父项未被删除吗?

转载 作者:可可西里 更新时间:2023-11-01 07:51:19 27 4
gpt4 key购买 nike

对于使用 Code First EF 5 beta 的应用程序,我有:

public class ParentObject
{
public int Id {get; set;}
public virtual List<ChildObject> ChildObjects {get; set;}
//Other members
}

public class ChildObject
{
public int Id {get; set;}
public int ParentObjectId {get; set;}
//Other members
}

必要时,相关的 CRUD 操作由存储库执行。

OnModelCreating(DbModelBuilder modelBuilder)

我已经设置好了:

modelBuilder.Entity<ParentObject>().HasMany(p => p.ChildObjects)
.WithOptional()
.HasForeignKey(c => c.ParentObjectId)
.WillCascadeOnDelete();

因此,如果一个 ParentObject 被删除,它的 ChildObjects 也会被删除。

但是,如果我运行:

parentObject.ChildObjects.Clear();
_parentObjectRepository.SaveChanges(); //this repository uses the context

我得到异常:

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.

这是有道理的,因为实体的定义包括被破坏的外键约束。

我能否将实体配置为在它成为孤立对象时“自行清理”,或者我必须从上下文中手动删除这些 ChildObject(在本例中使用 ChildObjectRepository)。

最佳答案

它实际上是支持的,但只有当你使用 Identifying relation 时才支持.它也适用于代码优先。您只需要为包含 IdParentObjectIdChildObject 定义复杂键:

modelBuilder.Entity<ChildObject>()
.HasKey(c => new {c.Id, c.ParentObjectId});

因为定义这样的键将删除自动递增 Id 的默认约定,您必须手动重新定义它:

modelBuilder.Entity<ChildObject>()
.Property(c => c.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

现在调用 parentObject.ChildObjects.Clear() 删除依赖对象。

顺便说一句。你的关系映射应该使用 WithRequired 来跟随你的真实类,因为如果 FK 不可为空,它就不是可选的:

modelBuilder.Entity<ParentObject>().HasMany(p => p.ChildObjects)
.WithRequired()
.HasForeignKey(c => c.ParentObjectId)
.WillCascadeOnDelete();

关于c# - EF 可以自动删除孤立的数据,其中父项未被删除吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10835439/

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