0


I have 2 tables A and B with relation n:n. I managed it by creating table C with 2 foreign keys and one primary key - 2 fk clustered.
When I try to delete entity in table A I get an error telling me that id of this entity is used in table C. Same for table B.

The DELETE statement conflicted with the REFERENCE constraint "FK_FlashCardTag_ToFlashCards". The conflict occurred in database "GuidanceDb", table "dbo.FlashCardTag", column 'IdFlashCard'.

How to force EF to delete rows from table C first if I have no model of table C (code first from db didn't create model for C)? Here is my table C and contex creation code. To be clear table A is FlashCards, B is Tags, C is FlashCardTag

CREATE TABLE [dbo].[FlashCardTag] (
    [IdFlashCard] INT           NOT NULL,
    [IdTag]       NVARCHAR (50) NOT NULL,
    CONSTRAINT [PK_FlashCardTag] PRIMARY KEY CLUSTERED ([IdFlashCard] ASC, [IdTag] ASC),
    CONSTRAINT [FK_FlashCardTag_ToTags] FOREIGN KEY ([IdTag]) REFERENCES [dbo].[Tags] ([Tag]),
    CONSTRAINT [FK_FlashCardTag_ToFlashCards] FOREIGN KEY ([IdFlashCard]) REFERENCES [dbo].[FlashCards] ([Id])
);

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {    modelBuilder.Entity<FlashCard>()
            .HasMany(e => e.Tags)
            .WithMany(e => e.FlashCards)
            .Map(m => m.ToTable("FlashCardTag").MapLeftKey("IdFlashCard").MapRightKey("IdTag"));
    }

To sum up: There is a parent entity which can have child which is used somewhere else. How to delete parent and child if child has no other references and don't delete child if has other refeneces. Thanks

  • Possible duplicate of [EF Many to Many cascading delete](https://stackoverflow.com/questions/36571266/ef-many-to-many-cascading-delete) – Progman Sep 14 '18 at 12:06
  • Found Programming Entity Framework - Code First book. Maybe I will find anserw there. Unfortunately other anserws from stack didn't solve my problem. – BlueCompany Sep 14 '18 at 12:17
  • 1
    Are the tables created with EF migration? What you need is `ON DELETE CASCADE` for the two FK relationships, EF normally does that for you. – Ivan Stoev Sep 14 '18 at 12:26
  • The anserw is no. But by adding ON DELETE CASCADE got different error so mby it resolved something. Will check it in 2 h. – BlueCompany Sep 14 '18 at 12:35
  • Yea, on delete cascade solved this problem. Many thanks! :) – BlueCompany Sep 14 '18 at 16:02

0 Answers0