Entity Framework 6.1: How to change clustered inde

2019-08-09 08:06发布

问题:

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:

CreateTable(
            "dbo.Invoices",
            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.

-----Update------
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?

回答1:

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)