具有可选关系的 EF Core 3.1 DeleteBehavior.SetNull 触发约束异常

EF Core 3.1 DeleteBehavior.SetNull with Optional Relationship fires Constraint Exception

我首先使用 EF Core 3.1 DB,尝试为可选关系设置 DeleteBehavior.SetNull,但我在 SaveChanges 上仍然遇到异常。

实体是:Patient,它在名为 Address 的字段中与 Address 具有可为空的关系。 这些实体是由这样的 scaffold-DbContext cmd 生成的(我删除了与问题无关的属性):

 public partial class Address
    {
        public Address()
        {
            Patient = new HashSet<Patient>();
        }

        public int Id { get; set; }
        ...

        public virtual ICollection<Patient> Patient { get; set; }
    }

和患者class:

public partial class Patient
    {
        public int Code { get; set; }          
        public int? Address { get; set; }
        ...

        public virtual Address AddressNavigation { get; set; }
    }

OnModelCreating函数中我有以下代码:

modelBuilder.Entity<Patient>(entity =>
        {
            ...

        entity.HasOne(d => d.AddressNavigation)
            .WithMany(p => p.Patient)
            .HasForeignKey(d => d.Address)
            .HasConstraintName("FK__Patient__Address__2F10007B")
            .OnDelete(DeleteBehavior.SetNull);
    });

当我尝试删除地址时,使用以下代码行:

using (ClinicContext ctx = new ClinicContext())
{
    var address = ctx.Address.Find(addressId);
    ctx.Remove(address);
    ctx.SaveChanges();
}

我得到以下异常:

The DELETE statement conflicted with the REFERENCE constraint "FK__Patient__Address__2F10007B". The conflict occurred in database "C:\USERS\USER\SOURCE\REPOS\CLINIC\DB\CLINIC.MDF", table "dbo.Patient", column 'Address'. The statement has been terminated

我在这里错过了什么?

正如@Jerry 所说,由于您使用的是 DB First,因此在执行 scaffold-DbContext commond 后,在生成的 DbContext 中添加 DeleteBehavior.SetNull 将不会对您的数据库产生任何影响。

您最好使用以下语句重新创建 table:

CREATE TABLE [dbo].[Patient] (
    [Code]    INT         IDENTITY (1, 1) NOT NULL,
    [Id]      VARCHAR (9) NOT NULL,
    [Address] INT         NULL,
    PRIMARY KEY CLUSTERED ([Code] ASC),
    FOREIGN KEY ([Address]) REFERENCES [dbo].[Address] ([Id]) ON DELETE SET NULL
);