title: EntityFramework CodeFirst: CASCADE DELETE for same table many-to-many relationship
body: <p>I have an entry removal problem with the EntityFramework and a many-to-many relationship for the same entity. Consider this simple example:</p>
  
  <p><em>Entity:</em></p>
  
  <pre><code>public class UserEntity {
      // ...
      public virtual Collection&lt;UserEntity&gt; Friends { get; set; }
  }
  </code></pre>
  
  <p><em>Fluent API Configuration:</em></p>
  
  <pre><code>modelBuilder.Entity&lt;UserEntity&gt;()
      .HasMany(u =&gt; u.Friends)
      .WithMany()
      .Map(m =&gt;
      {
          m.MapLeftKey("UserId");
          m.MapRightKey("FriendId");
          m.ToTable("FriendshipRelation");
      });
  </code></pre>
  
  <ol>
  <li>Am I correct, that it is not possible to define the <code>Cascade Delete</code> in Fluent API? </li>
  <li><p>What is the best way to delete a <code>UserEntity</code>, for instance <code>Foo</code>?</p>
  
  <p>It looks for me now, I have to <code>Clear</code> the <code>Foo</code>'s <code>Friends</code> Collection, then I have to load all other <code>UserEntities</code>, which contain <code>Foo</code> in <code>Friends</code>, and then remove <code>Foo</code> from each list, before I remove <code>Foo</code> from <code>Users</code>. But it sounds too complicateda. </p></li>
  <li><p>Is it possible to access the relational table directly, so that I can remove entries like this</p>
  
  <pre><code>// Dummy code
  var query = dbCtx.Set("FriendshipRelation").Where(x =&gt; x.UserId == Foo.Id || x.FriendId == Foo.Id);
  dbCtx.Set("FriendshipRelation").RemoveRange(query);
  </code></pre></li>
  </ol>
  
  <p>Thank you!</p>
  
  <p><strong><em>Update01:</em></strong></p>
  
  <ol start="4">
  <li><p>My best solution for this problem for know is just to execute the raw sql statement before I call <code>SaveChanges</code>:</p>
  
  <pre><code>dbCtx.Database.ExecuteSqlCommand(
      "delete from dbo.FriendshipRelation where UserId = @id or FriendId = @id",
      new SqlParameter("id", Foo.Id));
  </code></pre>
  
  <p>But the disadvantage of this, is that, if <code>SaveChanges</code> failes for some reason, the <code>FriendshipRelation</code> are already removed and could not be rolled back. Or am I wrong?</p></li>
  </ol>