title: Entity Framework Fluent API Mapping
body: <p><strong>Let's assume I have these tables:</strong></p>
  
  <pre><code>Role
  - RoleId
  - Name
  
  UserRole
  - UserId
  - RoleId
  
  User
  - UserId
  - Username
  
  UserEmail
  - UserId
  - EmailId
  - IsPrimary
  
  Email
  - EmailId
  - Address
  </code></pre>
  
  <p><strong>Now my model, should look something like this:</strong></p>
  
  <pre><code>public class Role {
      public int RoleId { get; set; }
      public string Name { get; set; }
      public virtual ICollection&lt;User&gt; Users { get; set; }
  }
  
  public class User {
      public int UserId { get; set; }
      public string Username { get; set; }
      public virtual ICollection&lt;Role&gt; Roles { get; set; }
      public virtual ICollection&lt;UserEmail&gt; UserEmails { get; set; }
  }
  
  public class UserEmail {
      public int UserId { get; set; }
      public int EmailId { get; set; }
      public bool IsPrimary { get; set; }
      public virtual User User { get; set; }
      public virtual Email Email { get; set; }
  }
  
  public class Email {
      public int EmailId { get; set; }
      public string Address { get; set; }
      public virtual ICollection&lt;UserEmail&gt; UserEmails { get; set; }
  }
  </code></pre>
  
  <p><strong>These are common and specific things I would like to do in this particular case:</strong></p>
  
  <p><strong>Add the primary keys:</strong></p>
  
  <pre><code>modelBuilder.Entity&lt;Role&gt;().HasKey(q =&gt; q.RoleId);
  </code></pre>
  
  <p>Will this have the same <em>effect</em> than using the <code>Key</code> attribute in the entity property? If so, why bother using the <code>modelBuilder</code> when using <em>Data Annotations</em> is shorter and easier to read/write? Is there any <em>convention</em> on when to use <em>Data Annotations</em> or <em>Fluent API</em>?</p>
  
  <p><strong>Add many to many relationships:</strong></p>
  
  <pre><code>modelBuilder.Entity&lt;Role&gt;()
      .HasMany(q =&gt; q.Users)
      .WithMany(q =&gt; q.Roles)
      .Map(q =&gt; {
                    q.MapLeftKey("RoleId");
                    q.MapRightKey("UserId");
                    q.ToTable("UserRoles");
                });
  </code></pre>
  
  <p><strong>Add one to many relationships:</strong></p>
  
  <pre><code>modelBuilder.Entity&lt;UserEmail&gt;()
      .HasRequired(q =&gt; q.User)
      .WithMany(q =&gt; q.UserEmails)
      .HasForeignKey(q =&gt; q.EmailId);
  </code></pre>
  
  <p>Is the last line required?</p>