【发布时间】: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