EFCore可为空的关系设置onDelete:ReferentialAction.Restrict

Dav*_*res 12 entity-framework ef-code-first entity-framework-core ef-core-2.0

我正在运行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; }

}
Run Code Online (Sandbox Code Playgroud)

我对这两个课程没有流利的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);
            });
Run Code Online (Sandbox Code Playgroud)

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

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

行为名称| 对记忆中依赖/子女的影响 | 对数据库中依赖/子代的影响

ClientSetNull(默认)| 外键属性设置为null | 没有

EF Core 2.0中的更改:在以前的版本中,Restrict会导致跟踪的从属实体中的可选外键属性设置为null,并且是可选关系的默认删除行为.在EF Core 2.0中,引入了ClientSetNull来表示该行为,并成为可选关系的默认值.调整Restrict的行为,从不对依赖实体产生任何副作用.

任何帮助,为什么会发生这种情况将非常感激.

Iva*_*oev 20

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

这是当前的映射:

DeleteBehavior    ReferentialAction
==============    =================
Cascade           Cascade
ClientSetNull     Restrict
Restrict          Restrict
SetNull           SetNull
Run Code Online (Sandbox Code Playgroud)

在您的情况下,关系是可选的,因此按照DeleteBehavior约定ClientSetNull映射到onDelete: Restrict,或换句话说,强制(启用)FK没有级联删除.

如果您想要不同的行为,则必须使用流畅的API,例如

modelBuilder.Entity<BigAwesomeDinosaurWithTeeth>()
    .HasMany(e => e.YummyPunyPrey)
    .WithOne(e => e.BigAwesomeDinosaurWithTeeth)
    .OnDelete(DeleteBehavior.SetNull); // or whatever you like
Run Code Online (Sandbox Code Playgroud)

  • 金色雕像应以您的名义制作; 谢谢伊万!文档真的让我失望了.我试图避免API,但我已经多次打破了这个分辨率,所以另一个不会受到伤害. (4认同)