Search code examples
c#entity-frameworkef-code-firstexpression-treessqlgeography

How to return DbGeography.Distance calculated value In Code First Entity Framework without losing strong typing?


Currently I have an entity that is "geolocatable" via a SqlGeography column that I can use via expressions for filtering and sorting. I am already able to get all entities within distance x of point y and sort by entities closest to (or furthest from) point y. However, in order to return the distance from the entity to y I have to recalculate the distance in the application because I have not yet determined how to materialize the result of the distance calculation from the database to the entities in the IQueryable. This is a mapped entity and a great deal of application logic surrounds the type of entity returned so projecting it into a dynamic object is not a viable option for this implementation (though I understand how that would work). I have also tried using an unmapped object that inherits from the mapped entity but that suffers the same problems. Essentially, as I understand it, I should be able to define the getter of an unmapped property to assign a computed value in a queryable extension IF I modify the expression tree that represents the IQueryable but the how escapes me. I've written expressions in this manner before but I think I need to be able to modify the existing select rather than just chaining on a new Expression.Call which is unexplored territory for me.

The following should code should properly illustrate the problem:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.Spatial; // from Microsoft.SqlServer.Types (Spatial) NuGet package
using System.Linq;

public class LocatableFoo
{
    [Key]
    public int Id { get; set; }

    public DbGeography Geolocation { get; set; }

    [NotMapped]
    public double? Distance { get; set; }
}

public class PseudoLocatableFoo : LocatableFoo
{
}

public class LocatableFooConfiguration : EntityTypeConfiguration<LocatableFoo>
{
    public LocatableFooConfiguration()
    {
        this.Property(foo => foo.Id).HasColumnName("id");
        this.Property(foo => foo.Geolocation).HasColumnName("geolocation");
    }
}

public class ProblemContext : DbContext
{
    public DbSet<LocatableFoo> LocatableFoos { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new LocatableFooConfiguration());

        base.OnModelCreating(modelBuilder);
    }
}

public class Controller
{
    public Controller(ProblemContext context) // dependency injection
    {
        this.Context = context;
    }

    private ProblemContext Context { get; set; }

    /* PROBLEM IN THIS METHOD:
     * Do not materialize results (ie ToList) and then calculate distance as is done currently <- double calculation of distance in DB and App I am trying to solve
     * Must occur prior to materialization
     * Must be assignable to "query" that is to type IQueryable<LocatableFoo>
     */
    public IEnumerable<LocatableFoo> GetFoos(decimal latitude, decimal longitude, double distanceLimit)
    {
        var point = DbGeography.FromText(string.Format("Point({0} {1})", longitude, latitude), 4326); // NOTE! This expects long, lat rather than lat, long.
        var query = this.Context.LocatableFoos.AsQueryable();

        // apply filtering and sorting as proof that EF can turn this into SQL
        query = query.Where(foo => foo.Geolocation.Distance(point) < distanceLimit);
        query = query.OrderBy(foo => foo.Geolocation.Distance(point));

        //// this isn't allowed because EF doesn't allow projecting to mapped entity
        //query = query.Select( foo => new LocatableFoo { Id = foo.Id, Geolocation = foo.Geolocation, Distance = foo.Geolocation.Distance(point) });

        //// this isn't allowed because EF doesn't allow projecting to mapped entity and PseudoLocatableFoo is considered mapped since it inherits from LocatableFoo
        //query = query.Select( foo => new PseudoLocatableFoo { Id = foo.Id, Geolocation = foo.Geolocation, Distance = foo.Geolocation.Distance(point) });

        //// this isn't allowed because we must be able to continue to assign to query, type must remain IQueryable<LocatableFoo>
        //query = query.Select( foo => new { Id = foo.Id, Geolocation = foo.Geolocation, Distance = foo.Geolocation.Distance(point) });

        // this is what I though might work
        query = query.SelectWithDistance(point);

        this.Bar(query);
        var results = query.ToList(); // run generated SQL
        foreach (var result in results) //problematic duplicated calculation
        {
            result.Distance = result.Geolocation.Distance(point);
        }

        return results;
    }

    // fake method representing lots of app logic that relies on knowing the type of IQueryable<T>
    private IQueryable<T> Bar<T>(IQueryable<T> foos)
    {
        if (typeof(T) == typeof(LocatableFoo))
        {
            return foos;
        }

        throw new ArgumentOutOfRangeException("foos");
    }
}

public static class QueryableExtensions
{
    public static IQueryable<T> SelectWithDistance<T>(this IQueryable<T> queryable, DbGeography pointToCalculateDistanceFrom)
    {
        /* WHAT DO?
         * I'm pretty sure I could do some fanciness with Expression.Assign but I'm not sure
         * What to get the entity with "distance" set
         */
        return queryable;
    }
}

Solution

  • The Distance field is logically not part of your table, since it represents a distance to a dynamically specified point. As such it should not be part of your entity.

    At this point if you want it being calculated on the db, you should create a Stored procedure, or a TVF (or sg else) that returns your entity extended with the distance. This way you can map the return type to an Entity. It is a clearer design to me btw.