title: Entity Framework: Check all relationships of an entity for foreign key use
body: <p>I have an entity, let's call it <code>CommonEntity</code> that has a primary key used as a foreign key in many other entities. As the application is developed these links will continue to grow.</p>
  
  <p>I'd like a way to see if <code>CommonEntity</code> can be safely deleted (i.e. it's not used by any other entities).</p>
  
  <p>I realise I can do</p>
  
  <pre><code>if(!ce.EntityA.Any() &amp;&amp; !ce.EntityB.Any() ... &amp;&amp; !ce.EntityN.Any())
  {
     //Delete
  }
  </code></pre>
  
  <p>but I'm hoping for a way to just check all of the relationships automatically, as I don't love the idea of having to come back and change this code manually every time we add a new relationship. Perhaps there is something in EF4+ that I'm not aware of?</p>
  
  <p>I thought it might be possible to use a transaction scope to just try and delete the object and roll it back if it fails, but I wasn't sure if there were any adverse side effects with this approach.</p>
  
  <p>Is there a better approach?</p>
  
  <p><strong>EDIT:</strong> Looks like VS2012 has used EF5 even though the project is .Net 4, so it has created the model with POCOs even though it was generated from a DB.</p>