如何在我的可视化C#web服务中为我的Android应用程序调用LINQ中的用户定义函数?

我目前正在开发一个应用程序,它将根据距离检索其他用户的位置。

我有一个数据库,以纬度和经度存储所有用户位置信息。 由于这两对纬度和经度之间的距离计算非常复杂,我需要一个函数来处理它。

from a in db.Location.Where(a => (calDistance(lat, longi, Double.Parse(a.latitude), Double.Parse(a.longitude)))<Math.Abs(distance) )) {...} 

但是,我收到以下错误:LINQ to Entities无法识别该方法,并且此方法无法转换为商店表达式。

我不知道如何将它翻译成商店表达式,而且,计算也需要数学库。

是否有任何方法可以让LINQ表达式调用我自己的函数?

也许有其他方法可以实现我的目标,任何人都可以帮忙吗?

我真的不知道LINQ,但假设你只能在查询中发送简单的约束,我会构造一个基本上与calDistance相反的方法 – 获取坐标和距离并将其转换为最小的边界框经度,最大经度,最小纬度和最大纬度。

您应该能够使用这些约束构建一个简单的查询来满足您的目的。

类似的东西(在这里使用Java):

 public double[] getCoordinateBounds(double distance, double longitude, double latitude) { double[] bounds = new double[4]; bounds[0] = longitude - distanceToLongitudePoints * (distance); bounds[1] = longitude + distanceToLongitudePoints * (distance); bounds[2] = latitude - distanceToLatitudePoints * (distance); bounds[3] = latitude + distanceToLatitudePoints * (distance); return bounds; } 

然后你可以构造一个查询。

 double[] bounds = getCoordinateBounds(distance, longi, lat); var nearbyUserLocations = from a in db.Location where longitude > bounds[0] and longitude < bounds[1] and latitude > bounds[2] and latitude < bounds[3] 

这会给你一个点而不是一个点的半径,但它可以是足够少的点,然后你可以处理它们并抛出你的半径以外的点。 或者你可能会认为一个盒子足以满足你的需要。

LinqToEntities不允许你调用函数,它甚至不允许ToString()

这不是Linq的事情,它是LinqToEntities的限制

您可以将代码作为存储过程或函数放入数据库,并使用ExecuteStoreQuery调用它

请参阅此处Entity Framework Code First是否支持存储过程?

你看到的问题是LINQ to SQL引擎试图从用户定义的函数注入T-SQL,但它不能。 一个(虽然令人讨厌)选项是检索所有位置,然后从该结果集计算。

 var locations = db.Location.ToList(); locations = locations.Where(a => (calDistance(lat, longi, Double.Parse(a.latitude), Double.Parse(a.longitude))).ToList();