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