title: Deleting Parent Entity of FK Constraint in Entity Framework & SQL Server
body: <p>I'm using Entity Framework with .NET 4.0 and SQL Server 2008.</p>
  <p>I have two entities <code>A</code> and <code>B</code>, <code>A</code> has many <code>B</code>'s (there's <code>a</code> field on <code>B</code> table, i.e. <code>B</code>-&gt;many to one -&gt;<code>A</code>). When I try to delete a specific parent entity <code>A</code>, the query fails</p>
  <blockquote>
  <p>A is parent entity, B is children entity.</p>
  </blockquote>
  <p>Here's the code I use for deletion of a particular <code>A</code> entity:-</p>
  <pre><code>var obj = (from A in context.As where A.id=someValue select A).First();
  context.As.DeleteObject(obj);
  context.SaveChanges();
  </code></pre>
  <p>However it throws the famous exception</p>
  <blockquote>
  <p>The DELETE statement conflicted with the REFERENCE constraint &quot;FK_bs_as&quot;. The conflict occurred in database &quot;myDb&quot;, table &quot;dbo.bs&quot;, column 'a'.</p>
  <p>The statement has been terminated.</p>
  </blockquote>
  <p>Then I looked at the foreign key constraint using SQL Server Management Studio and edited FK as follows:</p>
  <ul>
  <li>delete rule: cascade</li>
  <li>update rule: cascade</li>
  <li>enforce foreign key constraint: no</li>
  </ul>
  <p>and tried to set FK to <code>ON DELETE CASCADE</code>. However obviously there's still a problem with it.</p>
  <p>I don't want to fetch every damn child entity (<code>B</code>) of the parent entity (<code>A</code>) and delete them individually. That's too expensive when compared to executing a single SQL query.</p>