Entity Framework 6.1 - 使用 INCLUDE 语句创建索引

问题描述 投票:0回答:2

既然索引在实体框架 6.1 的最新测试版中可用,是否可以在代码优先方法中创建与此 SQL 语句相同的索引?

CREATE NONCLUSTERED INDEX [Sample1]
ON [dbo].[Logs] ([SampleId],[Date])
INCLUDE ([Value])
sql entity-framework indexing
2个回答
48
投票

严格来说,在 Code First 迁移中始终是可能的,因为您可以在迁移中运行 sql:

   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);
        }
    }

但我意识到您可能实际上是在问是否可以使用 6.1 中引入的 IndexAttribute 创建索引,但使用 Include 列 - 答案是“否”


0
投票

根据 Microsoft 文档,您可以像这样使用

IncludeProperties
函数:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Post>()
        .HasIndex(p => p.Url)
        .IncludeProperties(
            p => new { p.Title, p.PublishedOn });
}
© www.soinside.com 2019 - 2024. All rights reserved.