Entity Framework 6.1: How to change clustered index to another column?

c# entity-framework entity-framework-6


I have an entity like this:

public class Invoice 
    public Guid Id { get; set; }
    public int InvoiceNumber { get; set; }
    public string Caption { get; set; }

In my mapping file, I set the clustered index on InvoiceNumber and set a non-clustered index on the Id column.

public class InvoiceMapping : EntityTypeConfiguration<Invoice>
    public InvoiceMapping()
        HasKey(p => p.Id).Property(e => e.Id).HasColumnType(SqlDbType.UniqueIdentifier.ToString()).IsRequired()
            .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute() { IsClustered = false }));
        Property(e => e.Caption).HasColumnType(SqlDbType.NVarChar.ToString());
        Property(e => e.InvoiceNumber).HasColumnType(SqlDbType.Int.ToString()).HasColumnAnnotation("Index",
    new IndexAnnotation(new IndexAttribute() { IsClustered = true ,IsUnique = true}));


After migration, my generated class looks like:

            c => new
                    Id = c.Guid(nullable: false),
                    InvoiceNumber = c.Int(nullable: false),
                    Caption = c.String(maxLength: 4000),
            .PrimaryKey(t => t.Id)
            .Index(t => t.Id)
            .Index(t => t.InvoiceNumber, unique: true, clustered: true);

When I call Update-Database I get this error:

Cannot create more than one clustered index on table 'dbo.Invoices'. Drop the existing clustered index 'PK_dbo.Invoices' before creating another.

Neil answer is correct but id there any way that I don't need edit migration code and the code

.PrimaryKey(t => t.Id, null, true)

generate automatically?

6/30/2015 5:18:31 AM

Popular Answer

EntityFamework creates all primary keys as clustered indexes, you code above (the mapping) is specifying that the column has a primary key and a non-clustered index, you then try adding a clustered index to another column when the primary key will already be clustered.

AFAIK and without changing the migration it is not possible to create a non-clustered primary key, you would need to change the migration

.PrimaryKey(t => t.Id, null, true)
6/28/2015 6:17:33 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow