实体框架6.1:如何将聚集索引更改为另一列

本文关键字:一列 索引 框架 聚集 实体 | 更新日期: 2023-09-27 18:00:02

我有一个这样的实体:

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

在映射文件中,我在InvoiceNumber上设置了聚集索引,在Id列上设置了非聚集索引。

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}));
    }
}

迁移后,我生成的类看起来像:

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);

当我调用Update-Database时,我收到以下错误:

无法在表"dbo.Invoices"上创建多个聚集索引。请先删除现有聚集索引"PK_dbo.Invices",然后再创建另一个。

-----更新------
Neil答案是正确的,但我不需要编辑迁移代码和代码

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

自动生成?

实体框架6.1:如何将聚集索引更改为另一列

EntityFamework将所有主键创建为聚集索引,您在上面的代码(映射)中指定列具有主键和非聚集索引,然后在主键已经聚集时尝试将聚集索引添加到另一列。

AFAIK,如果不更改迁移,就不可能创建非集群主键,您需要更改迁移

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