简体   繁体   English

在多对多关系中删除实体会使关系表中的孤儿离开

[英]Deleting Entity in Many to Many Relationship Leaves Orphans in Relationship Table

When deleting records that are in a many to many relationship, the relationship table has orphan records. 删除多对多关系中的记录时,关系表中有孤立记录。 I have the following many to many relationship set up in my DbContext. 我在DbContext中建立了以下多对多关系。

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 property Cars: 我的所有者模型具有虚拟属性Cars:

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

My Car model has virtual property Owners: 我的汽车模型具有虚拟财产所有者:

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

I delete a Car as follows (db is my DbContext, car is a Car model). 我按以下方式删除Car(db是我的DbContext,car是Car模型)。

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

When I delete a Car, I was expecting all records in the table CarOwners with that CarId to be deleted as well but this is not the case. 当我删除汽车时,我希望具有该CarId的表CarOwners中的所有记录也将被删除,但事实并非如此。 Any advice? 有什么建议吗?

The solution was: 解决方案是:

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 are adding constraints to an existing table with data, you will have to make sure that orphan records are removed first... or else the ADD CONSTRAINT will fail. 注意:如果要将约束添加到具有数据的现有表中,则必须确保首先删除孤立记录...否则ADD CONSTRAINT将失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM