44

So now that Indexes are available in latest beta version of Entity Framework 6.1 is it even possible to create an index in code first approach that is equal to this SQL statement?

CREATE NONCLUSTERED INDEX [Sample1]
ON [dbo].[Logs] ([SampleId],[Date])
INCLUDE ([Value])
0

2 Answers 2

52

Strictly speaking it has been always possible in Code First Migrations because you can run sql in a migration:

   public partial class AddIndexes : DbMigration
    {
        private const string IndexName = "IX_LogSamples";

        public override void Up()
        {
            Sql(String.Format(@"CREATE NONCLUSTERED INDEX [{0}]
                               ON [dbo].[Logs] ([SampleId],[Date])
                               INCLUDE ([Value])", IndexName));

        }

        public override void Down()
        {
            DropIndex("dbo.Logs", IndexName);
        }
    }

But I realise that you are probably actually asking if you can create an index using the IndexAttribute introduced in 6.1, but with an Include column - the answer to that is "No"

Sign up to request clarification or add additional context in comments.

2 Comments

Yes IndexAttribute is what I was aiming for. But looks like we still can't have nice things =)
An important thing to note is that while this approach works, in that the index does get created, there's no difference in the Model in __MigrationHistory, so Database.CompatibleWithModel will return true both before and after this migration. So you can find yourself unexpectedly running against an unindexed database.
2

This question is regarding .NET Framework. People on .NET Core can use the IncludeProperties function like this:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Post>()
        .HasIndex(p => p.Url)
        .IncludeProperties(
            p => new { p.Title, p.PublishedOn });
}

See the Microsoft documentation

2 Comments

The question was about Entity Framework 6 not about Entity Framework Core
+1 while the question is not strictly about EF core, this question is still one of the first google results when searching for EF core, making this answer very helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.