Linq到EF – 不支持的function

我正在使用Linq进行查询,由Entity Framework数据源提供支持。

我收到以下错误:

LINQ to Entities无法识别方法’Double Sqrt(Double)’方法,并且此方法无法转换为存储表达式。

这是我的函数的简化版本(我的版本更复杂,使用ACos,sin,cos和其他C#Math类函数)。

var objects = from n in context.Products.Where(p => pr == r) let a = Math.Sqrt((double)n.Latitude) where a < 5 orderby a select n; return objects.Take(100).ToList(); 

我认为问题可能与Linq to EF(和SQL数据源)与Linq to SQL相比具有有限的受支持function集的情况有关。 我对此比较陌生,所以我不是百分百肯定。

任何人都可以给我指向正确的方向吗?

干杯,

尝试在SqlFunctions定义的SquareRoot函数

  var objects = from n in context.Products.Where(p => pr == r) let a = SqlFunctions.SquareRoot((double)n.Latitude) where a < 5 orderby a select n; return objects.Take(100).ToList(); 

如果您开始使用LINQ-to-objects学习LINQ,那么一旦开始使用LINQ-to-Entities,您将会遇到很多问题。

你可以做任何可以在LINQ-to-objects中编译的东西,因为LINQ-to-objects在编译时会转换为代码

LINQ-to-Entities(和LINQ-to-SQL)转换为表达式树 。 因此,只有特定LINQ提供程序允许的语法才有效。 在我的第一个“for real”LINQ-to-Entities表达式中编译得很好,我遇到了这个错误大约5次,因为我逐个删除了LINQ-to-Entities未处理的代码。

所以,当你看到这一点时,这是正常和常见的。 你需要每次都找到另一种方式。

您可以使用逻辑等效项来避免此问题:

 var objects = from n in context.Products.Where(p => pr == r) where (double)n.Latitude < 25 orderby a select n; return objects.Take(100).ToList(); 

您还可以将所有数据提取到客户端,然后使用LINQ-to-objects运行代码:

 var objects = from n in context.Products.Where(p => pr == r).ToList() let a = Math.Sqrt((double)n.Latitude) where a < 5 orderby a select n; return objects.Take(100).ToList(); 

最后,您应该能够在服务器上进行此数学运算。 查看System.Data.Objects.SqlClient.SqlFunctions SqlFunctions类 。 这些函数转换为表达式。 这特别看起来可能是票 。

请试试

 var objects = from n in context.Products.Where(p => pr == r) let a = Math.Pow((double)n.Latitude, 0.5) where a < 5 orderby a select n;