title: Mapping 1 to 0..1 in Entity Framework Code First
body: <p>I am trying to get 1 to 0..1 mapping to work in Entity Framework Code First, but keep getting the error:
  <em>A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'Id'.</em></p>
  
  <p>I have a MainLocation with a required Location, but as the Locations can have multiple child Locations, a MainLocation is not required in the Location object.</p>
  
  <p>The MainLocation has a similar relation to MainLocationAddress, but this is a 1 to 1 relation which in turn make up the same db table.</p>
  
  <p>The ER model should look like this:
  <img src="https://i.stack.imgur.com/bZKss.png" alt="enter image description here"></p>
  
  <p>My entities look like this:</p>
  
  <pre><code>[Table("MainLocation")]
  public class MainLocation : IEntity
  {
      [Key]
      [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
      public int Id { get; set; }
  
      [Required]
      public virtual MainLocationAddress Address { get; set; }
      [Required]
      public virtual Location Location { get; set; }
  }
  
  [Table("MainLocation")]
  public class MainLocationAddress : BaseAddress
  {
      [Key, ForeignKey("MainLocation")]
      [DatabaseGenerated(DatabaseGeneratedOption.None)]
      public int Id { get; set; }
      public virtual MainLocation MainLocation { get; set; }
  }
  
  public class Location : IEntity
  {
      public int Id { get; set; }
      public virtual Location ParentLocation { get; set; }
      public virtual ICollection&lt;Location&gt; ChildLocations { get; set; }
      protected virtual MainLocation MainLocation { get; set; }
      internal MainLocation GetMainLocation() { return this.MainLocation; }
      internal void SetMainLocation(MainLocation mainLocation) { MainLocation = mainLocation; }
  }
  </code></pre>
  
  <p>I have configured the associations in OnModelCreating in my DbContext class:</p>
  
  <pre><code>modelBuilder.Entity&lt;MainLocation&gt;()
              .HasRequired(x =&gt; x.Location)
              .WithOptional();
  
  modelBuilder.Entity&lt;MainLocation&gt;()
              .HasRequired(x =&gt; x.Address)
              .WithRequiredPrincipal();
  </code></pre>
  
  <p>PS! The MainLocation property on Location is protected because it should not be accessed directly. Instead I have a service-layer which gets the value from the Location or the inherited value from a ParentLocation. I have tried to change it to public, to see if it made any changes regarding the error I'm getting. </p>
  
  <p>Although I was able to extend .WithOptional() to .WithOptional(x => x.MainLocation), there were still no changes in the stated error.</p>