Search code examples
entity-frameworkspatialspatial-indexentity-framework-6.1ef-fluent-api

How to create spatial index using EF 6.1 fluent API


Well, the question is clear enough. Is it possible to create spatial indexes using Entity Framework 6.1 fluent API?


Solution

  • 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