[英]Compute and return distance in EF 6 / LINQ to Entities / DbGeography?
使用.NET 4.5.1和Entity Framework 6.0.2 ,我在下面得到了类似实体和查询的内容。
基本上我选择一个new
实体和捣碎的Distance
到它,当我宁愿查询Person
,并有Distance
嵌在那个人的Location
实体。
public class Person
{
public string Id { get; set; }
public string Name { get; set; }
[...]
public virtual ICollection<PersonLocation> PersonLocations { get; private set;}
}
public class Location
{
public int Id { get; set; }
public DbGeography Geocode { get; set; }
// ... I want calculated Distance right here
}
public class PersonLocation
{
public int PersonId { get; set; }
public int LocationId { get; set; }
public bool AcceptingNewClients { get; set; }
public Hours Hours { get; set; }
[...]
public virtual Person Person { get; private set; }
public virtual Location Location { get; private set; }
}
目前,我有这样的查询,其中_geo
是设置为所需搜索位置的DbGeography
,而radius
是int = 15
:
IQueryable<PersonWithDistance> results =
from pl in db.PersonLocations
let distance = pl.Location.Geocode.Distance(_geo)
where pl.Location.Geocode.IsEmpty == false
where distance <= radius * 1609.344
orderby distance
select new { Person = pl.Person, Distance = Math.Round((double)(distance / 1609.344), 1) };
我想要的是将Distance
添加到每个Location
实体,然后在查询中选择Person
实体。
有没有办法做到这一点? 我应该完全走一条不同的路线吗?
我最终要做的是:
public class Location
{
public int Id { get; set; }
public DbGeography Geocode { get; set; }
public double? Distance { get; set; }
}
在DbContext设置中,以便EF忽略与数据库相关的列:
Ignore(x => x.Distance);
搜索查询变为:
var results = (from pl in db.PersonLocations
let distance = pl.Location.Geocode.Distance(_geo)
where pl.Location.Geocode.IsEmpty == false
where distance <= radius * 1609.344
select pl.Person).Distinct();
最后:
var personsWithDistance = results.ToList();
foreach (Person p in personsWithDistance)
{
var pls = p.PersonLocations;
foreach (PersonLocation pl in pls)
{
if (pl.Location.Geocode != null)
pl.Location.Distance = Math.Round((double)(pl.Location.Geocode.Distance(_geo) / 1609.344), 1);
else
pl.Location.Distance = null;
}
}
// order by distance
personsWithDistance = personsWithDistance.OrderBy(r => r.PersonLocations.FirstOrDefault().Location.Distance).ToList();
return personsWithDistance;
本质上,我在Location
实体中创建了一个伪列/属性,并告诉DbContext忽略它。 我查询所需的结果集,然后手动更新属性并返回结果。
感觉不对,但是可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.