IntentArchitect / Support

A repository dedicated to handling issues and support queries
3 stars 0 forks source link

EntityFramework Core - OnDelete behavior for self referencing tables #102

Closed ivrljic closed 1 day ago

ivrljic commented 1 day ago

Ask a question

Hello,

We have a situation where one of our tables is having foreign key to itself to create a linked list. The created configuration for the domain item has its delete behavior set to Cascade but the EF is not agreeing with that. When we manually set the OnDelete behavior to Restrict the migration works but Intent overrides our changes. Is it possible to set some kind of Stereotype to define the delete behavior?

Section from domain item Configuration file: image

Error in the EF: Introducing FOREIGN KEY constraint 'FK_Products_Products_SuccessorId' on table 'Products' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint or index. See previous errors.

Database: SQL Server Framework: EF 8 Intent Template: Clean Architecture

joelsteventurner commented 1 day ago

Hi @ivrljic

Just double checking a few things and I'll get back to you shortly

joelsteventurner commented 1 day ago

@ivrljic

I have just run through a few scenarios our side, I see if I have a model like this if setting the OnDelete behaviour to be DeleteBehavior.Cascade, which is incorrect. I have logged this as a bug change this behaviour so that this type of Scenario results in a DeleteBehavior.Restrict

image

Can I confirm your model is similar, i.e. you have a composite owner relationship (i.e. Black Diamond) relationship into the Self referencing table?

Just want to make sure the Bug I have found, is the scenario you are experiencing.

As an interim workaround you can plavce an // IntentIgnore above that code to change the delete behaviour

            // IntentIgnore
            builder.HasMany(x => x.AggSelves)
                .WithOne()
                .HasForeignKey(x => x.ParentId)
                .IsRequired()
                .OnDelete(DeleteBehavior.Restrict);
ivrljic commented 1 day ago

Hello,

it is similar. We have an enitity that inherits a base entity that has a reference to itself as seen in the image.

In the Attribute overview on the Product table the Successor looks like this: image image

image

joelsteventurner commented 1 day ago

@ivrljic

I can also suggest, you could mapping this relationship as one of the following. Self-referencing tables is often more naturally an aggregational relationship (white diamond) rather than a compositional relationship (black diamond).

image

ivrljic commented 1 day ago

Yeah, this seems to fix it when both sides are 0..1. Thank you!