I have coded a C# MVC5 internet application, where I have a MapCompany
object that has a List<MapLocation>
. I have a DbSet<MapCompany>
as well as a DbSet<MapLocation>
. When I call the Delete Action result when trying to delete a MapCompany
object, I am getting the following error:
The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.MapLocations_dbo.MapCompanies_MapCompany_Id". The conflict occurred in database "TestDatabase", table "dbo.MapLocations", column 'MapCompany_Id'.
The statement has been terminated.
Do I need to remove all the associated MapLocations
when removing a MapCompany
object? If so, what is the easiest way to do this? Is there an easier/better way rather than looping through each object, and removing each object manually? Also, at a future stage, each MapLocation
will have many MapLocationItem
objects.
Manual
Delete the items manually. This is sometimes the preferred option as it gives you full control.
Cascaded Deletes
You can set the foreign key relationship to cascade deletes. This means that deleting the parent record will delete all records from the table that references it. To enable cascaded deletes on a table, read this answer .
Alternatively if you are using code first development, you can enable cascading deletes using the fluent API:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MapCompany>()
.HasOptional(a => a.MapLocations)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}
Here is a good discussion on the pros/cons of cascaded deletes: What are the Pros and Cons of Cascading delete and updates?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.