0

I have the following entities:

public class CompanyRelationshipEntity
{
    public int ParentCompanyId { get; set; }
    public int ChildCompanyId { get; set; }
    public CompanyEntity? ParentCompany { get; set; }
    public CompanyEntity? ChildCompany { get; set; }
}

And

public class CompanyEntity
{
    public int Id { get; set; }
    public CompanyRelationshipEntity? ChildCompany{ get; set; }
    public CompanyRelationshipEntity? ParentCompany { get; set; }
}

With the following relationship defined on the CompanyRelationshipTable:

        model.ToTable("CompanyRelationship");
        model.HasKey(x => new { x.ParentCompanyId, x.ChildCompanyId });

        model.HasOne(e => e.ChildCompany)
            .WithOne(e => e.ChildCompany)
            .HasForeignKey<CompanyRelationshipEntity>(x => x.ChildCompanyId)
            .OnDelete(DeleteBehavior.Cascade);

        model.HasOne(e => e.ParentCompany)
            .WithOne(e => e.ParentCompany)
            .HasForeignKey<CompanyRelationshipEntity>(x => x.ParentCompanyId)
            .OnDelete(DeleteBehavior.Cascade);

When trying to create the database I get the following:

Introducing FOREIGN KEY constraint 'FK_CompanyRelationship_Company_ParentCompanyId' on table 'CompanyRelationship' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints

If I change this relationship to ClientCascade, it works. The expected behaviour I want to achieve is to remove the record from the CompanyRelationship table if either the Parent or Child company is deleted but ideally I don't want to have to load this relationship before doing so.

Mark Walsh
  • 3,241
  • 1
  • 24
  • 46
  • This may help: [Ef 6 How To Set Two Foreign Keys To Same Table](https://www.faqcode4u.com/faq/526598/ef-6-how-to-set-two-foreign-keys-to-same-table) – Eskandar Abedini Jul 01 '22 at 13:16
  • [Entity Framework Code First - two Foreign Keys from same table](https://stackoverflow.com/questions/5559043/entity-framework-code-first-two-foreign-keys-from-same-table) and [Entity Framework Core - Configure Two Foreign Keys to the Same Table](https://www.youtube.com/watch?v=V2uDU47uezY) – Eskandar Abedini Jul 01 '22 at 13:19
  • Here you can find another detailed answer too [Defining multiple Foreign Key for the Same table in Entity Framework Code First](https://entityframework.net/knowledge-base/28570916/defining-multiple-foreign-key-for-the-same-table-in-entity-framework-code-first) – Eskandar Abedini Jul 01 '22 at 13:26
  • None of these achieve the behavior I want. – Mark Walsh Jul 18 '22 at 16:15

0 Answers0