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

时间:2018-01-30 12:51:47

标签: 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; }

}

我对这两个班级没有流利的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);
            });

当文档说它应该以 ClientSetNull

处理它时,为什么会生成 onDelete:ReferentialAction.Restrict
  

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的行为,从不对依赖实体产生任何副作用。

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

1 个答案:

答案 0 :(得分:18)

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

这是当前的映射:

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

在您的情况下,关系为optional,因此约定为DeleteBehavior的{​​{1}}映射到ClientSetNull,换句话说,强制< / em>(启用)FK没有级联删除。

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

onDelete: Restrict