Note that there are some explanatory texts on larger screens.

plurals
  1. POThe DELETE statement conflicted with the SAME TABLE REFERENCE constraint with Entity Framework
    primarykey
    data
    text
    <p>I have a table with a self reference where the ParentId is an FK to the ID (PK).<br> Using EF (code-first), I've set up my relationship as follows: </p> <pre><code>this.HasOptional(t =&gt; t.ParentValue) .WithMany(t =&gt; t.ChildValues) .HasForeignKey(t =&gt; t.ParentId); </code></pre> <p>When I try to delete the children and its parent, the DELETE commands EF issues to the database are not in the order I expected them to go - it attempts to delete the parent record first. </p> <p>I realize that I have a couple of options here (neither of which I like): </p> <ol> <li>Delete child records first, do a full save/commit, and then delete parent record. With the complexity of my model and the logic that maintains it, this isn't an option - can't issue multiple commit commands whenever I want.</li> <li>Dissolve the relationship before deleting anything. This seems like a more sensible solution, but again, I have to issue separate commit with an UPDATE statement before the DELETEs. I want to avoid multiple save/commit calls.</li> <li>Use a trigger to delete children prior to deleting parent record. But I'd like to avoid triggers and their problematic nature as much as possible. </li> </ol> <p>So the question is.. is there a way to enforce the deletion of children before the parent record? Perhaps I'm missing some sort of an explicit way of telling EF that it needs to take care of these children before the parent? Maybe there's a way to direct EF to delete in a descending order of IDs? I don't know.. thoughts?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload