c# - 如何在不丢失强类型的情况下返回代码优先 Entity Framework 中的 DbGeography.Distance 计算值?

标签 c# entity-framework ef-code-first expression-trees sqlgeography

目前,我有一个可通过 SqlGeography 列进行“地理定位”的实体,我可以通过表达式使用该实体进行过滤和排序。我已经能够获取距离 yx 范围内的所有实体,并按距离 y 点最近(或最远)的实体进行排序。但是,为了返回从实体到 y 的距离,我必须在应用程序中重新计算距离,因为我还没有确定如何具体化从数据库到实体的距离计算结果在 IQueryable 中。这是一个映射的实体,大量的应用程序逻辑围绕着返回的实体类型,因此将它投影到一个动态对象中对于这个实现来说不是一个可行的选择(尽管我理解它是如何工作的)。我也尝试过使用从映射实体继承的未映射对象,但它遇到了同样的问题。本质上,据我了解,如果我修改表示 IQueryable 的表达式树,但我不知道如何逃脱,我应该能够定义未映射属性的 getter 以在可查询扩展中分配计算值。我以前用这种方式编写过表达式,但我认为我需要能够修改现有的选择,而不是仅仅链接一个新的 Expression.Call,这对我来说是未开发的领域。

以下应代码应正确说明问题:

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

最佳答案

换行怎么样

var results = query.ToList();

var results = query
                .Select(x => new {Item = x, Distance = x.Geolocation.Distance(point)}
                .AsEnumerable() // now you just switch to app execution
                .Select(x => 
                {
                    x.Item.Distance = x.Distance; // you don't need to calculate, this should be cheap
                    return x.Item;
                })
                .ToList();

关于c# - 如何在不丢失强类型的情况下返回代码优先 Entity Framework 中的 DbGeography.Distance 计算值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33642584/

相关文章:

c# - 已发布的控制台应用程序上没有 .NET Core 2.0 应用程序设置

c# - 如果我不想加载主窗体,如何处理 Winforms 中的命令行参数?

c# - Foreach循环检查空字符串并为其赋值c#

c# - Entity Framework 6 两个不同的集合引用同一个实体

c# - Required 属性对导航属性有什么影响吗?

entity-framework - EF 6 基于代码的迁移 : Add not null property to existing entity

c# - 如果一组符号仅重复,如何使正则表达式匹配?

asp.net-mvc - EF 代码优先模块化设计

.net - EF 5 Code first Entities FirstOrDefault 方法返回 null

entity-framework - Entity Framework Code First 创建的列中字符串与其他数据类型的可为空性