title: How do I define Foreign Key Optional Relationships in FluentAPI/Data Annotations with the Entity Framework?
body: <p>I have a (sample) application with the following code:</p>
  
  <pre><code>public class Posts
  {
  
      [Key]
      [Required]
      public int ID { get; set; }
  
      [Required]
      public string TypeOfPost { get; set; }
  
      public int PollID { get; set; }
      public virtual Poll Poll { get; set; }
  
      public int PostID { get; set; }
      public virtual Post Post { get; set; }
  
  }
  </code></pre>
  
  <p>Basically, I don't know if there is a better way of doing this, but, I have a list of Posts, and, people can choose if it is a <code>Poll</code> or a <code>Post</code>, As Entity Framework doesn't work with Enums, I just store it as a string in <code>TypeOfPost</code> and then in the application, I programmatically query either Poll or Post based on the value of <code>TypeOfPost</code>.</p>
  
  <p>I don't think there is anyway of setting "Only one required" or similar, so, I handle all the checking and stuff in the application. (If anyone knows a better way, please say!).</p>
  
  <p>Anyway, the problem is, I can get this working fine by going in to SQL Management Studio and manually editing the schema to allow nulls - but, I just can't work out how to do this in the FluentAPI, and need some help.</p>
  
  <p>I have tried both of the following:</p>
  
  <pre><code>modelBuilder.Entity&lt;Post&gt;()
      .HasOptional(x =&gt; x.Poll).WithOptionalDependent();
  
  modelBuilder.Entity&lt;Post&gt;()
      .HasOptional(x =&gt; x.Poll).WithOptionalPrincipal();
  </code></pre>
  
  <p>The first one seems to create an additional column in the database that allows nulls, and the second one doesn't appear to do anything.</p>
  
  <p>I believe the first one is the one I need, but, I need to use it in combination with [ForeignKey] in the <code>Post</code> Class. If I am correct here, Should the [ForeignKey] go on the virtual property, or the ID of the property?</p>
  
  <p>In addition, what is the actual difference between <code>WithOptionalDependent</code> and <code>WithOptionalPrincipal</code>? - I have read on MSDN, but, I really do not understand the difference.</p>