我有以下代码
query = query.Where(device => GetDeviceDistanceFromGeocode(geocode, device) <= distanceMetres);
private static double GetDeviceDistanceFromGeocode(Geocode geocode, Device device)
{
return Math.Pow(
Math.Pow(device.Address.Geocode.Easting - geocode.Easting, 2) +
Math.Pow(device.Address.Geocode.Northing - geocode.Northing, 2)
, 0.5);
}
但是它会引发异常,因为 linq 无法识别我的函数,这迫使我一次性完成整个查询表达式。
Exception[LINQ to Entities does not recognize the method
'Double DistanceOfDeviceFromGeocode(Geocode, Device)' method,
and this method cannot be translated into a store expression.]
是否可以像我在这里尝试做的那样将查询表达式分成多个部分?当查询很大时,它不是很可读。
编辑:
这是评论中要求的完整查询。
return query.Where(device =>
Math.Pow(
Math.Pow(device.Address.Geocode.Easting - geocode.Easting, 2) +
Math.Pow(device.Address.Geocode.Northing - geocode.Northing, 2)
, 0.5)
<= distanceMetres);
基本上我认为这不是很可读,所以想把它分解成多个部分,但从提供的链接来看,这似乎是不可能的。
在 c++ 中,我可以将其中的一些分解成一个宏,但不幸的是,这不是 c# 的一个特性。
根据建议,我已将代码更新为此,效果非常好,并大大提高了代码的可读性!
return query.Where( DevicesWithinDistanceFromGeocode(distanceMetres, geocode) );
}
public Expression<Func<Device, bool>> DevicesWithinDistanceFromGeocode(double distance, Geocode geocode)
{
return device => ( SqlFunctions.SquareRoot(
SqlFunctions.Square((double)(device.Address.Geocode.Easting - geocode.Easting)) +
SqlFunctions.Square((double)(device.Address.Geocode.Northing - geocode.Northing))
) <= distance );
}