title: Entity Framework (Code First) One to Many and One to One relations (with two entities). How to?
body: <p>I'm trying to do this with EF Code First:</p>
  
  <p><img src="https://i.stack.imgur.com/epdf9.png" alt="database model"></p>
  
  <p>There area two tables: Users and Areas. One User belongs to one required area and one Area can have zero or one User (as administrator). Then:</p>
  
  <p>Users *..1 Areas and
  Users 0..1 Areas</p>
  
  <p>The Users class:</p>
  
  <pre><code>public class User {
      public int UserId { get; set; }
      public string Name { get; set; }
  
      [ForeignKey("Area")]
      public int AreaId { get; set; }
      [InverseProperty("Users")]
      public virtual Area Area { get; set; }
  
      public virtual Area AreaTitular { get; set; }
  }
  </code></pre>
  
  <p>The Areas class:</p>
  
  <pre><code>public class Area {
      public int AreaId { get; set; }
      public string Name { get; set; }
  
      public List&lt;User&gt; Users { get; set; }
  
      [ForeignKey("User")]
      public int? UserId { get; set; }
      [InverseProperty("AreaTitular")]
      public virtual User User{ get; set; }
  }
  </code></pre>
  
  <p>And the error on update-database command:</p>
  
  <blockquote>
    <p>Unable to determine the principal end of an association between the types 'TestEntityFrameworkCodeFirst.Model.Area' and 'TestEntityFrameworkCodeFirst.Model.User'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.</p>
  </blockquote>
  
  <p>Any help will be very appreciated :)</p>
  
  <p>I'm not completely sure if this is ok:</p>
  
  <pre><code>protected override void OnModelCreating(DbModelBuilder modelBuilder) {
      modelBuilder.Entity&lt;Area&gt;()
          .HasOptional(i =&gt; i.User)
          .WithOptionalDependent();
      base.OnModelCreating(modelBuilder);
  }
  </code></pre>
  
  <p>Just added this on the OnModelCreating on the Context class. And this is how it looks in SQL Server:</p>
  
  <p><img src="https://i.stack.imgur.com/sxcVS.png" alt="Database"></p>