Index Attribute in ASP.Net Core

I was attempting to add an [Index] attribute to a field on a project I started recently that’s using ASP.Net Core 2.2. Though the number of records in the table for now is not terribly large I was just planning for the future.

Despite adding the needed using statements to get access to the attribute I could not get Intellisense to quit squawking about it.

Turns out there’s a difference between Entity Framework and Entity Framework Core in this case. Seems this feature was left out because of issues.

Leaving out the index attribute from the migration and then adding the index to the column after updating the database is easy enough to do but presents problems. If you have to back out that last migration for some reason and then reapply you’ll have to remember to perform the step to re-add the index. The same problem occurs if you try and run the code on a new installation elsewhere.

Instead, after the migration has been create and before it’s used to update the database just manually modify the migration’s Up() method to add the needed index.


protected override void Up(MigrationBuilder migrationBuilder)
{
    // Table creation code created by migration here

    migrationBuilder.CreateIndex(
        "IX_SomeRecords_Name",
        "SomeRecords",
        "Name"
    );
}

You should be able to update the database consistently now and in the future without any additional steps.

This entry was posted in C#, Programming and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published.