我想获取用户输入的位置 x 英里内的所有组织的列表。这将转换为长/纬度位置。
组织以long 和lat 存储在数据库中。
我正在使用带有实体框架的 MVC 和带有存储库模式的工作单元来访问数据集。
这是我的EntityRepository:
public IQueryable<T> All
{
get
{
return dbSet;
}
}
public IQueryable<T> AllIncluding(params System.Linq.Expressions.Expression<Func<T, object>>[] includeProperties)
{
IQueryable<T> query = dbSet;
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
return query;
}
public IEnumerable<T> Where(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
{
return dbSet.Where(predicate).AsEnumerable();
}
为了查询我的数据上下文中的数据,我为每个实体使用一个服务类,一个 UOW 被注入到每个服务中。对组织的服务要求是:
public class OrgService :IOrgService
{
private IUnitOfWork _UoW;
public OrgService(IUnitOfWork UoW)
{
_UoW = UoW;
}
public Organisation GetOrgByID(int OrgID)
{
return _UoW.OrganisationRepo.Find(OrgID);
}
public IList<Organisation> GetAllOrgs()
{
return _UoW.OrganisationRepo.All.ToList();
}
public IList<Organisation> GetOrgsByLocation(double lat, double lng, int range)
{
/// I need to return a list of all organisations within X miles
}
}
所有其他查询都按应有的方式工作,但是我没有尝试编写 GetOrgsByLocation() 方法。这是我认为我需要得到结果的查询:
var userLocation = new GeoCoordinate(lat, lng);
var result = _UoW.OrganisationRepo.Where(x => new GeoCoordinate(x.Latitude, x.Longitude))
.Where(x => x.GetDistanceTo(userLocation) < radius).ToList();
当我尝试运行此查询时,我得到:
“无法将类型 system.device.location.geoCoordinate 隐式转换为 bool”
任何人都可以帮忙吗?
** 更新 - 工作解决方案 **
var userLocation = new GeoCoordinate(lat, lng);
var nearbyOrganizations = _UoW.OrganisationRepo.All.ToList()
.Select(x => new
{ //use an anonymous type or any type you want
Org = x,
Distance = new GeoCoordinate(x.Latitude, x.Longitude).GetDistanceTo(userLocation)
})
.Where(x => x.Distance < 50000)
.ToList();
foreach (var organisation in nearbyOrganizations)
{
Console.WriteLine("{0} ({1:n0} meters)", organisation.Org, organisation.Distance);
}
多亏了以下对此解决方案的帮助,尽管似乎必须查询所有对象才能使其正常工作,但似乎查询更适合在数据库上运行,我将不得不对此进行更多研究。