title: Entity Framework Code First, Clustered Indexes & Composite Keys
body: <p>I am attempting to add a non-unique, clustered index on one of the columns used by a composite key in a table using EF's Code First approach. So far, I have the following models. Note the <code>IX_PackageTargetPackageId</code> index attribute on the <code>PackageTarget.PackageId</code> property I am trying to add:</p>
  
  <pre><code>public class Package
  {
      [Key]
      public int Id { get; set; }
      [Required]
      [Index("IX_PackageName", IsUnique = true)]
      public string Name { get; set; }
  }
  
  public class Target
  {
      [Key]
      public int Id { get; set; }
      [Required]
      public string Value { get; set; }
  }
  
  public class PackageTarget
  {
      [Key]
      [Column(Order = 0)]
      [Index("IX_PackageTargetPackageId", IsClustered = true)]
      public int PackageId { get; set; }
  
      [Key]
      [Column(Order = 1)]
      public int TargetId { get; set; }
  
      [ForeignKey("PackageId")]
      public virtual Package Package { get; set; }
  
      [ForeignKey("TargetId")]
      public virtual Target Target { get; set; }
  }
  </code></pre>
  
  <p>I have the following migration which was automatically generated for me:</p>
  
  <pre><code>CreateTable(
      "dbo.PackageTargets",
      c =&gt; new
          {
              PackageId = c.Int(nullable: false),
              TargetId = c.Int(nullable: false),
          })
      .PrimaryKey(t =&gt; new { t.PackageId, t.TargetId })
      .ForeignKey("dbo.Packages", t =&gt; t.PackageId, cascadeDelete: true)
      .ForeignKey("dbo.Targets", t =&gt; t.TargetId, cascadeDelete: true)
      .Index(t =&gt; t.PackageId, clustered: true, name: "IX_PackageTargetPackageId")
      .Index(t =&gt; t.TargetId);
  
  CreateTable(
      "dbo.Packages",
      c =&gt; new
          {
              Id = c.Int(nullable: false, identity: true),
              Name = c.String(nullable: false)
          })
      .PrimaryKey(t =&gt; t.Id)
      .Index(t =&gt; t.Name, unique: true, name: "IX_PackageName");
  
  CreateTable(
      "dbo.Targets",
      c =&gt; new
          {
              Id = c.Int(nullable: false, identity: true),
              Value = c.String(nullable: false)
          })
      .PrimaryKey(t =&gt; t.Id);
  </code></pre>
  
  <p>The only amendment I have made to the migration is to add <code>clustered: false</code> to the <code>PackageTargets</code> primary key as I would like the <code>IX_PackageTargetPackageId</code> index to be clustered instead.</p>
  
  <p>After the above amendment, I am still unable to run the migration as the following exception occurs:</p>
  
  <pre><code>Cannot create more than one clustered index on table 'dbo.PackageTargets'. 
  Drop the existing clustered index 'PK_dbo.PackageTargets' before creating another.
  </code></pre>
  
  <p>From my migration, I cannot see other clustered indexes are present. Am I missing something?</p>