title: Entity Framework Fluent Mapping Optional One-To-One
body: <p>I need to set up a relationship that is currently a one-to-many:</p>
  
  <pre><code>public class Foo
  {
      public int FooId { get; set; }
      public int? BarId { get; set; }
      ...
      public virtual Bar Bar { get; set; }
  }
  
  public class Bar
  {
      public int BarId { get; set; }
      ...
      public virtual ICollection&lt;Foo&gt; Foos { get; set; }
  }
  
  public FooMap()
  {
      HasKey(e =&gt; e.FooId);
      Property(e =&gt; e.FooId.IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
      Property(e =&gt; e.BarId).IsOptional();
      ...
      HasOptional(e =&gt; e.Bar).WithMany(Foos).HasForeignKey(e =&gt; e.BarId);
  }
  
  public BarMap()
  {
      HasKey(e =&gt; e.BarId);
      Property(e =&gt; e.BarId.IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
      ...
      HasMany(e =&gt; e.Foos).WithOptional(e =&gt; e.Bar).HasForeignKey(e =&gt; e.BarId);
  }
  </code></pre>
  
  <p>However, in reality, Bar can only be assigned to a single Foo. Is it possible to set this up so I have a single Foo navigation property in Bar rather than a collection of Foos? I still want my tables to render:</p>
  
  <pre><code>Foos
  - FooId
  - BarId (null)
  - ...
  
  Bars
  - BarId
  - ...
  </code></pre>
  
  <p>and I want my classes to be:</p>
  
  <pre><code>Foo
  - FooId
  - BarId
  - ...
  - Bar
  
  Bar
  - BarId
  - ...
  - Foo
  </code></pre>
  
  <p>I've been fiddling around with WithOptionalDependant and WithOptionalPrincipal, but can't find the correct combination. Any help is appreciated!</p>