gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:56:34 25 4
gpt4 key购买 nike

目前,我有一个可通过 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com