我在处理可选的一对一和一对多关系时遇到了一些问题。启用其中 1 个可以正常工作,但同时启用这两个会导致“可能的循环级联异常”。
我有一个“客户”,它有多个“交付地址”和一个“访问地址”。所以对于地址,我有一个可选的 DeliverAddressForCustomer 和一个可选的 VisitAddressForCustomer。
结果如下表:
CREATE TABLE [dbo].[Customer]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY
[Name] NVARCHAR(50) NOT NULL,
)
CREATE TABLE [dbo].[Address]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY,
[Street] NVARCHAR(50) NOT NULL,
[DeliverAddressForCustomerId] INT NULL,
[VisitAddressForCustomer] INT NULL,
CONSTRAINT [FK_Address_Customer_DeliverAddressForCustomerId] FOREIGN KEY ([DeliverAddressForCustomerId]) REFERENCES [Customer]([Id]),
CONSTRAINT [FK_Address_Customer_VisitAddressForCustomerId] FOREIGN KEY ([VisitAddressForCustomerId]) REFERENCES [Customer]([Id])
)
这适用于以下映射:
this.ToTable("Address");
this.Property(t => t.Id).HasColumnName("Id");
this.Property(t => t.Postcode).HasColumnName("Postcode");
this.Property(t => t.DeliverAddressForCustomerId).HasColumnName("DeliverAddressForCustomerId");
// Relationships
this.HasOptional(t => t.DeliverAddressForCustomer)
.WithMany(t => t.DeliverAddresses)
.HasForeignKey(d => d.DeliverAddressForCustomerId)
.WillCascadeOnDelete(true);
this.HasOptional(a => a.VisitAddressForCustomer)
.WithOptionalDependent(k => k.VisitAddress)
.Map(x => x.MapKey("VisitAddressForCustomerId"))
.WillCascadeOnDelete(true);
现在,如果我将两个 'WillCascadeOnDelete' 都设置为 true,它将与现有数据库一起使用,但如果我想创建数据库则不行......我收到以下异常消息:
在表 'Address' 上引入 FOREIGN KEY 约束 'FK_dbo.Address_dbo.Address_Customer_VisitAddressForCustomerId' 可能会导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。
但这对我来说没有意义,因为如果我删除了 deliveryAddress 或 visitAddress,客户应该在此设置中保持不变。所以不应该有循环级联。