title: Entity Framework - Validation of Foreign Keys
body: <p>Having the following <code>TestClass</code>:</p>
  
  <pre><code>[Table("xyz")]
  public partial class TestClass{
      [Key]
      public int key {get; set;}
      [ForeignKey("key")]
      public virtual ICollection&lt;ExternalClass&gt; externalClasses{get; set;}
  
      public IEnumerable&lt;ValidationResult&gt; Validate(ValidationContext validationContext)
      {
          ... 
      }
  }
  </code></pre>
  
  <p>How do I need to set that class up to match my following requirements:</p>
  
  <ul>
  <li>I want to test the model with Entity Framework unit testing</li>
  <li>In production, the <code>externalClasses</code> shouldn't get saved (should already be in database)</li>
  <li>The EF must assure, that each external class exists in DB. If not, throw exception.</li>
  </ul>
  
  <p>My first thought was to set the foreign objects null and request the database within the validate method to check if the foreign-key(s) exist. But this approach doesn't work that good with Unit Testing and in addition to that in my opinion it's not that clean to have database requests within a model.</p>
  
  <p>Does anyone have an idea how to handle that on a clean way using the EF?</p>