Add Index with Include Entity Framework Core

This post explaines how to add index to EF Core with extra columns included from code.

When creating indexes with code first migrations in Entity Framework Core you can create an index on a table by adding the following to your DbContext:

protected override void OnModelCreating(ModelBuilder modelBuilder)

        .HasIndex(t =&gt; new { t.Column1, t.Column2}); } 

However when you want to include some columns in your indexes, there is no notation for it. To do that you have to make an empty migration and then add the create index by hand. You can add the code to create the index in the Up and Down part of your new migration:

        protected override void Up(MigrationBuilder migrationBuilder)
CREATE NONCLUSTERED INDEX [IX_Table_Colum1__Column2] ON [dbo].[Table]
    [Column1] ASC
        protected override void Down(MigrationBuilder migrationBuilder)

When adding this kind of SQL migration code, you have to keep track of it when you want to recreate the Migrations.

Image: Sandhill Crane Silhouettes, November Sunrise, by NPS/Patrick Myers

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.