Asp.net Core Entity Framework cannot find IndexAttribute

This seems to have changed since you asked the question. jsakamoto has implemented NuGet package that allows you to keep your [Index] attribute. The only difference is order of variables; you can no longer have Order=0 as your last variable but rather do:

[Index("IX_TreeFiddy", 0, IsUnique = false)]
public string LochNessMonster { get; set; }

[Index("IX_TreeFiddy", 1, IsUnique = false)]
public int CentsGiven { get; set; }

Override OnModelCreating()

// Override "OnModelCreating"
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    // .. and invoke "BuildIndexesFromAnnotations"!
    modelBuilder.BuildIndexesFromAnnotations();
}

Here is link to: IndexAttribute for .NET Core NuGet package


I am still in the process of getting familiar with Core tools; further research revealed that this feature is not supported but they would consider a pull request.

https://github.com/aspnet/EntityFrameworkCore/issues/4050

The work-around

The recommended way to add indexes to Code First models in the absence of IndexAttribute is to use Entity Framework Fluent API. For example the following could be added to your context (derived from DbContext):

    /// <summary>
    /// Creates database structure not supported with Annotations using Fluent syntax.
    /// </summary>
    /// <param name="optionsBuilder">The configuration interface.</param>
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Story>().HasIndex(
            story => new { story.Date, story.Published }).IsUnique(false);
    }

This creates a two-column index for Story.Date and Story.Published that's not unique. Following this change, use:

dotnet ef migrations add <name>
dotnet ef database update

It's interesting to note what kind of Migration code is generated to create this index (you could use this directly to customize your migrations to create index instead of adding code to your Context class):

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.CreateTable(
        name: "Stories",
        columns: table => new
        {
            Id = table.Column<int>(nullable: false)
                .Annotation("Autoincrement", true),
            Author = table.Column<string>(maxLength: 64, nullable: true),
            Date = table.Column<DateTime>(nullable: false),
            Published = table.Column<bool>(nullable: false),
            Title = table.Column<string>(nullable: true)
        },
        constraints: table =>
        {
            table.PrimaryKey("PK_Stories", x => x.Id);
        });

    migrationBuilder.CreateIndex(
        name: "IX_Stories_Date_Published",
        table: "Stories",
        columns: new[] { "Date", "Published" });
}

The fruit of such labors:

SQLiteStudio showing the generated table