Deleting an entity in many ways Many deprive orphans of orphans in a relationship table

When deleting entries that are in many respects, the relationship table has spelling entries. In my DbContext, I have many different relationships.

protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Car>() .HasMany(u => u.Owners) .WithMany(l => l.Cars) .Map(ul => { ul.MapLeftKey("CarId"); ul.MapRightKey("OwnerId"); ul.ToTable("CarOwners"); }); } 

My owner model has virtual ownership Cars:

 public virtual ICollection<Car> Cars { get; set; } 

My Car model is virtual property

 public virtual ICollection<Owner> Owners { get; set; } 

I delete the car as follows (db is my DbContext, car is the model of the car).

 db.Cars.Remove(car); db.SaveChanges() 

When I delete a Car, I expected that all entries in the CarOwners table will also be deleted with CarId, but this is not the case. Any tips?

+6
source share
1 answer

Decision:

 ALTER TABLE [dbo].[CarOwners] WITH CHECK ADD CONSTRAINT [FK_Car_Owners] FOREIGN KEY([CarId]) REFERENCES [dbo].[Car] ([Id]) ON DELETE CASCADE GO ALTER TABLE [dbo].[CarOwners] WITH CHECK ADD CONSTRAINT [FK_Owner_Cars] FOREIGN KEY([OwnerId]) REFERENCES [dbo].[Owner] ([Id]) ON DELETE CASCADE GO 

NOTE. If you add constraints to an existing data table, you will need to make sure that the orphan records are deleted first ... or else ADD CONSTRAINT will fail.

+1
source

Source: https://habr.com/ru/post/923491/


All Articles