gpt4 book ai didi

sql-server - EF Core - 从父实体删除子实体时出现错误 "The association between entities has been severed"

转载 作者:行者123 更新时间:2023-12-05 02:44:04 24 4
gpt4 key购买 nike

我有两个实体如下所示:

public class LiftPlan
{
public int Id { get; set; }
public ICollection<PlanConsiderationEntity> PlanConsiderations { get; set; }
}

public class PlanConsideration
{
public int Id { get; set; }

public int PlanId { get; set; }
public LiftPlan LiftPlan { get; set; }
}

关系配置为-

builder
.HasOne(e => e.LiftPlan)
.WithMany(e => e.PlanConsiderations)
.HasForeignKey(e => e.PlanId)
.OnDelete(DeleteBehavior.NoAction);

当我添加像这样的子实体时它会起作用-

LiftPlan.PlanConsiderations.Add(planConsideration)

但是当我尝试删除子实体时

LiftPlan.PlanConsiderations.Remove(planConsideration)

它给了我错误-

The association between entities 'LiftPlanEntity' and 'PlanConsiderationEntity' with the key value '{PlanId: 1}' has been severed but the relationship is either marked as 'Required' or is implicitly required because the foreign key is not nullable. If the dependent/child entity should be deleted when a required relationship is severed, then setup the relationship to use cascade deletes.

我尝试使用 -

dbContext.PlanConsiderations.Remove(planConsideration)

它使用 dbContext 工作。

我不确定为什么会这样。它应该可以工作,因为我们没有删除父项。如果我们要删除父级,那么这个错误是有道理的。但是对于子删除,它不应该发生。

注意:
我知道通过将关系设置为级联删除或将外键设置为 null 将起作用,但我不想这样做。

最佳答案

问题是,当您从 LiftPlan 中删除 PlanConsideration 时,需要从给定的 PlanConsideration 中删除 PlanId ,但 int PlanId 属性不可为空,因此这是不可能的。

当您从 context.PlanConsiderations 中删除一个 PlanConsideration 时,这会起作用,因为该场景不会出现上述问题。

如果将 int PlanId 更改为 int? PlanId(当然还有更新数据库架构),它应该可以正常工作而不会引发任何错误。

我不太明白的一件事是:

Note: I know by setting relationship to cascade deletes or making foreign key as null will work but I don't want to do that.

如果您的意思是要保持该外键不可为 null,强制它引用 LiftPlan,我不确定它是如何工作的。我相当有信心,从 EF Core 的角度来看,这是相同的关系,只要实体上存在这些显式属性,就需要以两种方式表示。但也许有人会就此纠正我。


如果我没有告诉您任何新信息,请告诉我,以便我删除答案。 :)

关于sql-server - EF Core - 从父实体删除子实体时出现错误 "The association between entities has been severed",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66597610/

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