如何在 Lambda .NET 语法中调用用户定义的函数
本文关键字:用户 调用 定义 函数 语法 Lambda NET | 更新日期: 2023-09-27 18:33:56
好的,这是我的问题。我有数据库表BloodCenters
,其中有latitude
和longitude
字段。我想通过使用Linq Lambda语法来查询这些表,方法是检索相对于某个点在给定半径内的血液中心。
我正在使用这段代码,但它仍然给我错误(在 Where 谓词内):
public static List<BloodCenter> GetAllNearby(int latitude, int longitude, int radius, int limit){
List<BloodCenter> res = null;
res = new DBEntities().BloodCenters.Where(b =>
Util.distance(latitude, longitude, b.Latitude, b.Longitude, "K") <= radius).Take(limit);
return res;
}
Util.distance 是一个函数,返回 2 个纬度和经度之间的距离。编辑因此,我不能将自己的函数放在 Where 谓词中。但是我可以使用 SQL 语法计算距离吗?这是我Util.Distance
实现:
public static double distance(double lat1, double longi1, double lat2, double longi2, string unit){
var theta = longi1 - longi2;
var dist = Math.Sin(DegreeToRadian(lat1)) * Math.Sin(DegreeToRadian(lat2)) +
Math.Cos(DegreeToRadian(lat1)) * Math.Cos(DegreeToRadian(lat2)) * Math.Cos(DegreeToRadian(theta));
dist = Math.Acos(dist);
dist = RadianToDegree(dist);
var miles = dist * 60 * 1.1515;
unit = unit.ToUpper();
if (unit.Equals("K"))
return miles * 1.609344;
else if (unit.Equals("N"))
return miles * 0.8684;
else
return miles;
}
这是
行不通的,因为Util.distance
是在 C# 代码中实现的,查询图面不知道如何将其转换为 SQL(或者即使有可能)。
直接的解决方法是从数据库中获取所有记录并将谓词应用于实例,如下所示:
res = new DBEntities().BloodCenters.ToList()
.Where(b => Util.distance(latitude, longitude, b.Latitude, b.Longitude, "K") <= radius)
.Take(limit);
return res;
当然,获取所有记录也不是最好的主意,但有时根本没有其他方法。
您可以尝试在Where
谓词中内联Util.distance
逻辑。如果逻辑只能使用"简单"操作(如基本数学)来表示,则查询表面将能够将其转换为SQL,并且一切都会顺利进行。
以下是可以自动转换为 SQL 的所有方法的列表。
您必须
将DBEntities().BloodCenters
转换为IEnumerable
或List
或本地存储的其他内容。Linq to SQL 将 C# 转换为 SQL - 因此您只能使用 SQL 服务器提供的函数。
另一种方法是使用可翻译语句模拟函数或在数据库(存储过程或类似)中实现它