【问题标题】:Entity Framework 6.1: How to change clustered index to another column?Entity Framework 6.1:如何将聚集索引更改为另一列?
【发布时间】:2015-06-28 06:00:08
【问题描述】:

我有一个这样的实体:

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.Invoices”。

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

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

自动生成?

【问题讨论】:

    标签: c# entity-framework entity-framework-6


    【解决方案1】:

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

    AFAIK 并且在不更改迁移的情况下无法创建非集群主键,您需要更改迁移

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

    【讨论】:

    • 这段代码是否自动生成?
    猜你喜欢
    • 2016-02-19
    • 2014-05-13
    • 2016-12-21
    • 2013-03-30
    • 1970-01-01
    • 2023-03-20
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多