首页 > 解决方案 > 如何首先使用代码在 EF Core 中创建列存储索引

问题描述

我们想开始一个新项目,我们决定从一开始就在一些表中使用列存储索引和聚集索引,我们如何使用 Code First EF Core 3.1 做到这一点?

标签: ef-code-firstef-core-3.1columnstore

解决方案


  • 您应该将主键更改为非聚集索引:

    entity.HasKey(e => e.Id).IsClustered(false);
    
  • 然后将手动迁移添加到迁移文件夹我添加一个带有名称的文件30000000000001_AddMyColumnStoreIndex.cs并在文件中添加以下代码

using DDFHandler;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using System.Diagnostics.CodeAnalysis;

namespace MyNameSpace
{
    [DbContext(typeof(MyApplicationContext))]
    [Migration("30000000000001_AddMyColumnStoreIndex")]
    public class V1_AddMyColumnStoreIndex : Migration
    {
        protected override void Up([NotNullAttribute] MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql("CREATE CLUSTERED COLUMNSTORE INDEX [cci] ON [sch].[TableName]");
        }
        protected override void Down(MigrationBuilder migrationBuilder)
        {
        }
    }
}

请注意,您应该将[sch].[TableName]替换为您的表名和架构


推荐阅读