【问题标题】:EF Core 3 Clustered indexing using fluent API not working使用流畅 API 的 EF Core 3 聚集索引不起作用
【发布时间】:2020-06-30 01:44:15
【问题描述】:

我有一个启用了 EF 核心代码优先迁移的 .Net core 3.1 API,我试图在非 PK 列上添加聚集索引。

我有一个 Vehicle 实体:

public class Vehicle 
{
    // PK and has clustered index by default
    [Key]
    public int Id { get; set; }

    // FK and needs to be clustered
    public long CompanyId { get; set; }
    [ForeignKey(nameof(CompanyId))]
    public virtual Company Company { get; set; }
}

我为上述模型创建了代码优先迁移,然后更新了数据库。 此时,该表的 PK 为 Id,带有聚集索引,CompanyId 与 FK 一样。

为了从Id 中删除聚集索引并在CompanyId 上添加聚集索引,我在OnModelCreating() 方法的Fluent API 中编写了以下内容

// Remove ClusteredIndex from PK
modelBuilder.Entity<Vehicle>().HasIndex(m => m.Id).IsUnique(true).IsClustered(false);
// Add clustered index on CompanyId
modelBuilder.Entity<Vehicle>().HasIndex(m => m.CompanyId).IsUnique(false).IsClustered(true);

当我运行 API 时,我可以看到上面的 ccode 确实执行了,但它对 SQL DB 没有影响,并且没有根据需要更改索引。

我在这里缺少什么?如何在CompanyId 列上添加聚集索引?

【问题讨论】:

    标签: c# entity-framework-migrations ef-fluent-api ef-core-3.1


    【解决方案1】:

    在迁移中使用良好的旧 SQL 来解决此问题。

    首先为MigrationBuilder创建了一个扩展方法:

    public static void CreateNonPKClusteredIndex(this MigrationBuilder migrationBuilder,
        string tableNameWithSchema,
        string pkConstraintName, string pkColumnName,
        string nonClusteredIndexName, string clusteredColumnName)
    {
        // Change PK clustered index to non clustered
        migrationBuilder.Sql($"ALTER TABLE {tableNameWithSchema} DROP CONSTRAINT {pkConstraintName}");
        migrationBuilder.Sql($"ALTER TABLE {tableNameWithSchema} ADD CONSTRAINT {pkConstraintName} PRIMARY KEY NONCLUSTERED({pkColumnName})");
    
        // Update CompanyId index to clustered index
        migrationBuilder.Sql($"Drop Index {nonClusteredIndexName} on {tableNameWithSchema}");
        migrationBuilder.Sql($"CREATE CLUSTERED INDEX[{nonClusteredIndexName}] ON {tableNameWithSchema}({clusteredColumnName} ASC)");
    }
    

    然后在各自的迁移中简单地在Up() 中调用它:

    migrationBuilder.CreateNonPKClusteredIndex("Core.Vehicles",
        "PK_Vehicles", "Id",
        "IX_Vehicles_CompanyId", "CompanyId");
    

    结果:

    【讨论】:

      猜你喜欢
      • 2021-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 2011-05-21
      • 2015-09-28
      • 2020-08-04
      • 1970-01-01
      相关资源
      最近更新 更多