title: Code First Entity Framework Virtual and Foreign Key Confusions
body: <p>So I have some POCO classes:</p>
  
  <pre><code>public class Device : DbEntity
  {
    public string DeviceName {get;set;}
  }
  public class AUT : DbEntity
  {
    public string ApplicationName {get;set;}
  }
  public class Setup : DeviceAppDbEntity
  {
    public bool Worked {get;set;}
  }
  
  public class DbEntity
  {
    public Guid ID {get;set;}
  }
  public class DeviceAppDbEntity : DbEntity
  {
    public virtual AUT ApplicationUnderTesting {get;set;}
    public virtual Device DeviceUnderTesting {get;set;}
  }
  </code></pre>
  
  <p>So if I want to delete an AUT (Application) then I will almost certainly get an error because Setup has a foreign key to App. I've been told that if you add</p>
  
  <pre><code>public class DeviceAppDbEntity : DbEntity
  {
    public virtual AUT ApplicationUnderTesting {get;set;}
    public Guid ApplicationUnderTestingId {get;set;} // THIS LINE ADDED
  
    public virtual Device DeviceUnderTesting {get;set;}
  }
  </code></pre>
  
  <p>Then cascade delete will be enabled. Is this correct?</p>
  
  <p>When I now access the Setups</p>
  
  <pre><code>_repository.Setups.FirstOrDefault(x =&gt; x.ID.Equals(setupID));
  </code></pre>
  
  <p>The navigation property <code>virtual AUT</code> &amp; <code>virtual Device</code> should be automatically filled out?? Will the <code>Guid ApplicationUnderTestingId</code> be automatically filled out?</p>
  
  <p>When I want to save my <code>Setup</code> entity, then can I just fill out the nav property? or do I have to fill out the <code>Guid ApplicationUnderTestingId</code> field as well, or do I do the reverse and only fill out the <code>Guid ApplicationUnderTestingId</code>?</p>
  
  <pre><code>entityToSave.AUT = _repository.AUTs.FirstOrDefault(x =&gt; x.ID.Equals(vm.AppID));
  </code></pre>
  
  <p>or</p>
  
  <pre><code>entityToSave.ApplicationUnderTestingId= vm.AppID;
  entityToSave.AUT = _repository.AUTs.FirstOrDefault(x =&gt; x.ID.Equals(vm.AppID));
  </code></pre>
  
  <p>or</p>
  
  <pre><code>entityToSave.ApplicationUnderTestingId= vm.AppID;
  </code></pre>
  
  <p>This is kinda confusing.. It gets worse when you define a <code>List&lt;entities&gt;</code>, because when you delete the entity which contains the list. It complains about the entities within the list having relationships, how do you enable cascade delete on these?</p>
  
  <pre><code>public class Blog: DbEntity
  {
    public string Name {get;set;}
    public virtual Member {get;set;}
  
    public List&lt;Comment&gt; Comments {get;set;}
  }
  </code></pre>
  
  <p>I know it seems like a lot of questions, but it revolves around one topic in entity framework.Thank you for anytime spent answering my questions.</p>