I have some issues getting cascading to work on my optional one-to-one and one-to-many relation. Enabling 1 of them works fine but enabling both results in a 'possible circular cascading exception'.
I have a 'Customer' which has multiple 'DeliverAddresses' and one 'VisitAddress'. So for address I have an optional DeliverAddressForCustomer and an optional VisitAddressForCustomer.
this results in the following tables:
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 works with the following mapping:
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);
Now if I have both 'WillCascadeOnDelete' set to true, it will work with an existing DB but not if I want to create the DB... I get the following exception message:
Introducing FOREIGN KEY constraint
'FK_dbo.Address_dbo.Address_Customer_VisitAddressForCustomerId' on table 'Address' may cause
cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON
UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
But this doesn't make sense to me since if I delete a deliveryAddress or a visitAddress, customer should stay untouched in this setting. So there should be no circular cascading.