gpt4 book ai didi

c# - 将 LINQ to Entities 分成多个部分

转载 作者:行者123 更新时间:2023-11-30 16:21:59 26 4
gpt4 key购买 nike

我有以下代码

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 );
}

最佳答案

技术上 there are ways to do it ,但是由于 Linq 无法直接将您的自定义代码转换为 SQL,因此他们需要将所有结果返回给 Linq,然后评估自定义方法。

由于您在 Where 子句中使用它,我假设您希望检索相对较少数量的记录。在那种情况下,我建议在 SQL 中对您的条件进行编码,在存储过程或标量值函数中,然后在您的 Linq-to-Entities 查询中使用该存储过程/函数。

关于c# - 将 LINQ to Entities 分成多个部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12822446/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com