How to create spatial index using EF 6.1 fluent API

一曲冷凌霜 提交于 2019-11-30 19:55:58

Short answer- No, it is not. I have seen this tangentially referenced throughout blogs and have found no concrete examples of implementation. It seems to be related to the fact that spatial indexes are filtered indexes, which are not supported in Entity Framework.

As support for my answer I constructed a POC console app with the most recent version of Entity Framework (6.1). I took the following steps

  1. Created a model that had a property of the type DbGeography
  2. Enabled automatic migrations
  3. Ran Update-Database -verbose insuring migration with the addition of an index was run. The index used the following:

    modelBuilder.Entity<LocationEntity>().Property(t => t.Coordinates).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("ix_locationentity_coordinates")));

No indexes were created, but neither did the app crash. I could try permutations on this, but my example seems to follow the convention of entity framework: Official Fluent Documentation

The only way I know to do this is through a "custom" migration. In EF6, I add a migration (in the example below it's named "V1"), resulting in an new migration with empty Up() and Down() methods. You can then add custom SQL commands to these methods before running update-database to put these in the "normal" migrations flow.

It's possible to modify an existing migration to add these features, but I prefer in practice to keep my automatically scaffolded migrations separate from my customized ones.

public partial class V1 : DbMigration
{
    public override void Up()
    {
        Sql("CREATE SPATIAL INDEX [IX_UserProfileAddresses_Location] ON [dbo].[UserProfileAddresses](Location)");
    }

    public override void Down()
    {
        Sql("DROP INDEX [IX_UserProfileAddresses_Location] ON [dbo].[UserProfileAddresses]");
    }
}

Not an ideal method, but not too bad since it does follow the "normal" migrations pattern for EF.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!