gpt4 book ai didi

entity-framework - EF Core 可为空关系设置删除 : ReferentialAction. 限制

转载 作者:行者123 更新时间:2023-12-04 00:41:08 25 4
gpt4 key购买 nike

我正在运行 efcore 2.0.1。

我有一个模型:

public class BigAwesomeDinosaurWithTeeth
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }

public ICollection<YummyPunyPrey> YummyPunyPrey { get; set; }
}
public class YummyPunyPrey
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public Guid? BigAwesomeDinosaurWithTeethId { get; set; }

[ForeignKey("BigAwesomeDinosaurWithTeethId")]
public BigAwesomeDinosaurWithTeeth BigAwesomeDinosaurWithTeeth { get; set; }

}

我对这两个类没有流利的api。但是当我生成迁移时
constraints: table =>
{
table.PrimaryKey("PK_YummyPunyPrey", x => x.Id);
table.ForeignKey(
name: "FK_YummyPunyPrey_BigAwesomeDinosaurWithTeeth_BigAwesomeDinosaurWithTeethId",
column: x => x.BigAwesomeDinosaurWithTeethId,
principalTable: "BigAwesomeDinosaurWithTeeth",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});

为什么它会生成 onDelete: ReferentialAction.Restrict 当文档说它应该将它作为 ClientSetNull 处理时

https://docs.microsoft.com/en-us/ef/core/saving/cascade-delete

Behavior Name | Effect on dependent/child in memory | Effect on dependent/child in database

ClientSetNull (Default) | Foreign key properties are set to null | None

Changes in EF Core 2.0: In previous releases, Restrict would cause optional foreign key properties in tracked dependent entities to be set to null, and was the default delete behavior for optional relationships. In EF Core 2.0, the ClientSetNull was introduced to represent that behavior and became the default for optional relationships. The behavior of Restrict was adjusted to never have any side effects on dependent entities.



任何有关为什么会发生这种情况的帮助将不胜感激。

最佳答案

EF Core 2.0.1 元数据和迁移使用不同的枚举来指定删除行为 - 分别 DeleteBehavior ReferentialAction .虽然第一个有据可查,但第二个和两者之间的映射没有(在撰写本文时)。

这是当前的映射:

DeleteBehavior    ReferentialAction
============== =================
Cascade Cascade
ClientSetNull Restrict
Restrict Restrict
SetNull SetNull

在你的情况下,关系是 optional ,因此 DeleteBehavior按照惯例是 ClientSetNull映射到 onDelete: Restrict ,或者换句话说,强制(启用)FK 无级联删除。

如果你想要不同的行为,你必须使用流畅的 API,例如
modelBuilder.Entity<BigAwesomeDinosaurWithTeeth>()
.HasMany(e => e.YummyPunyPrey)
.WithOne(e => e.BigAwesomeDinosaurWithTeeth)
.OnDelete(DeleteBehavior.SetNull); // or whatever you like

关于entity-framework - EF Core 可为空关系设置删除 : ReferentialAction. 限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48521939/

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