Reputation: 5817
I have two tables. These are Design and Like. One design can have many likes and one like should be related to one Design.
When I try to delete a Design it throws me an exception:
The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.DesignLike_dbo.Design_DesignId". The conflict occurred in database "XXXDB", table "dbo.DesignLike", column 'DesignId'. The statement has been terminated.
modelBuilder.Entity().HasMany(x => x.Likes).WithRequired(x => x.Design).WillCascadeOnDelete(false);
I dont even try to delete related entities ? Why I get this exception ?
Upvotes: 0
Views: 125
Reputation: 8656
It sounds like you've set up your database to enforce a valid foreign key constraint on the DesignId
column in your DesignLike
table.
If you try and delete a Design
, you're deleting the DesignId
which is referenced by all the DesignLikes
as a foreign key. If you were allowed to do that, you'd find your database in an inconsistent state - your foreign key wouldn't really have meaning if there isn't a guarantee it references a valid record.
You could either remove the now invalid foreign key from your child objects, or set add a Deleted
/ Visible
flag to your Design
if you wish keep the Design
and corresponding DesignLikes
Upvotes: 0
Reputation: 2629
You are trying to delete an object that still has child objects. And the foreign key on the child objects will give you this exception.
You should decouple the child objects are link them to another parent before deleting the current one. Or include them in a cascaded delete.
In your case the design you are trying to delete has at least one like with the foreign key set to the id of your design. When you now delete the design and cascading is off it will violate the foreign key constraint of your like.
Upvotes: 2