title: EntityFramework Fluent API Foreign Key ordering
body: <p>How to set column order for foreign key properties, so all columns will be generated in my custom order rather than default alphabetical one? </p>
  
  <p>I want to use pure code first aproach without any annotation attributes and I don't want to include foreign key id columns (like UserId, RoleId etc) in my entity.</p>
  
  <p>Let's say I have following configuration class:</p>
  
  <pre><code>public class UserRoleEntityConfiguration: EntityTypeConfiguration&lt;UserRole&gt;
  {
      public UserRoleEntityConfiguration()
      {
          HasRequired(p =&gt; p.User).WithMany(p =&gt; p.Roles);
          HasOptional(p =&gt; p.Company).WithMany(p =&gt; p.Users);
          HasRequired(p =&gt; p.Role).WithMany(p =&gt; p.Users);
      }
  }
  </code></pre>
  
  <p>EF will generate following table:</p>
  
  <pre><code>create table [dbo].[UserRoles] (
  [Id] [int] not null identity,
  ...
  [CompanyId] [int] null,
  [RoleId] [int] not null,
  [UserId] [int] not null,
  primary key ([Id]));
  </code></pre>
  
  <p>But I want:</p>
  
  <pre><code>create table [dbo].[UserRoles] (
  [Id] [int] not null identity,
  ...
  [UserId] [int] not null,    
  [CompanyId] [int] null,
  [RoleId] [int] not null,
  primary key ([Id]));
  </code></pre>
  
  <p><strong>UPDATE:</strong>
  Found a workaround using protected foreign key properties:</p>
  
  <pre><code>public class UserRole : AuditableEntity&lt;int&gt;
  {
      protected int? CompanyId { get; set; }
  
      protected int RoleId { get; set; }
  
      protected int UserId { get; set; }
  
      public virtual Company Company { get; set; }
  
      public virtual Role Role { get; set; }
  
      public virtual User User { get; set; }
  
      public class AccessExpressions
      {
          public static readonly Expression&lt;Func&lt;UserRole, int?&gt;&gt; CompanyId = x =&gt; x.CompanyId;
          public static readonly Expression&lt;Func&lt;UserRole, int&gt;&gt; RoleId = x =&gt; x.RoleId;
          public static readonly Expression&lt;Func&lt;UserRole, int&gt;&gt; UserId = x =&gt; x.UserId;
      }
  }
  
  public class UserRoleEntityConfiguration: EntityTypeConfiguration&lt;UserRole&gt;
  {
      public UserRoleEntityConfiguration()
      {
          Property(UserRole.AccessExpressions.UserId).HasColumnOrder(8);
          HasRequired(p =&gt; p.User).WithMany(p =&gt; p.Roles).HasForeignKey(UserRole.AccessExpressions.UserId);
  
          Property(UserRole.AccessExpressions.CompanyId).HasColumnOrder(9);
          HasOptional(p =&gt; p.Company).WithMany(p =&gt; p.Users).HasForeignKey(UserRole.AccessExpressions.CompanyId);
  
          Property(UserRole.AccessExpressions.RoleId).HasColumnOrder(10);
          HasRequired(p =&gt; p.Role).WithMany(p =&gt; p.Users).HasForeignKey(UserRole.AccessExpressions.RoleId);
      }
  }
  </code></pre>
  
  <p>Is there any other way to achieve the same thing?</p>